package com.eshop.modules.order.service.impl;

import org.slf4j.LoggerFactory;
import java.lang.invoke.SerializedLambda;
import com.eshop.modules.user.service.dto.UserDto;
import com.eshop.modules.order.service.dto.StoreOrderCartInfoDto;
import com.eshop.modules.order.service.dto.StoreOrderStatusDto;
import com.eshop.modules.order.domain.StoreOrderStatus;
import com.eshop.utils.OrderUtil;
import com.eshop.exception.BadRequestException;
import java.io.IOException;
import com.eshop.utils.FileUtil;
import javax.servlet.http.HttpServletResponse;
import com.eshop.exception.EntityExistException;
import com.eshop.common.utils.QueryHelpPlus;
import com.eshop.modules.order.service.dto.StoreOrderDto;
import com.github.pagehelper.PageInfo;
import org.springframework.data.domain.Pageable;
import com.eshop.modules.order.service.dto.StoreOrderQueryCriteria;
import cn.hutool.core.bean.BeanUtil;
import com.eshop.modules.order.service.dto.OrderTimeDataDto;
import com.eshop.modules.order.service.dto.CountDto;
import com.eshop.modules.order.service.dto.OrderCountDto;
import com.eshop.modules.template.domain.ShippingTemplatesFree;
import com.eshop.enums.ShippingTempEnum;
import com.eshop.modules.order.service.dto.TemplateDto;
import java.util.HashMap;
import com.eshop.modules.template.domain.ShippingTemplatesRegion;
import com.eshop.modules.template.domain.ShippingTemplates;
import com.eshop.modules.product.vo.StoreProductQueryVo;
import com.alibaba.fastjson.JSONObject;
import com.eshop.enums.CouponEnum;
import com.eshop.enums.ProductTypeEnum;
import com.eshop.tools.domain.AlipayConfig;
import com.eshop.tools.domain.vo.TradeVo;
import com.eshop.modules.order.service.dto.StatusDto;
import com.alibaba.fastjson.JSON;
import com.eshop.modules.order.vo.UserOrderCountVo;
import com.eshop.modules.order.vo.OrderDataVo;
import com.eshop.modules.order.vo.ShoperOrderTimeDataVo;
import java.util.LinkedHashMap;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.Arrays;
import com.eshop.api.BusinessException;
import com.eshop.enums.OrderStatusEnum;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.eshop.modules.activity.domain.StorePink;
import com.eshop.modules.order.domain.EshopExpress;
import com.eshop.modules.order.vo.StoreOrderQueryVo;
import org.springframework.context.ApplicationEvent;
import com.eshop.event.TemplateEvent;
import cn.hutool.core.date.DateUtil;
import java.util.Date;
import com.eshop.event.TemplateListenEnum;
import com.eshop.event.TemplateBean;
import com.eshop.enums.BillDetailEnum;
import com.eshop.modules.product.domain.StoreProductReply;
import com.eshop.modules.order.domain.StoreOrderCartInfo;
import org.springframework.cache.annotation.CacheEvict;
import java.util.concurrent.TimeUnit;
import com.eshop.enums.OrderLogEnum;
import java.util.Collection;
import com.eshop.exception.ErrorRequestException;
import com.eshop.modules.shop.domain.SystemStore;
import com.eshop.enums.AppFromEnum;
import cn.hutool.core.util.IdUtil;
import com.eshop.enums.PayTypeEnum;
import java.util.ArrayList;
import com.eshop.modules.order.param.OrderParam;
import com.eshop.modules.activity.domain.StoreCouponUser;
import java.util.Iterator;
import com.eshop.modules.order.service.dto.CacheDto;
import cn.hutool.core.util.NumberUtil;
import com.eshop.enums.OrderInfoEnum;
import cn.hutool.core.util.StrUtil;
import com.eshop.modules.order.vo.ComputeVo;
import com.eshop.modules.order.service.dto.PriceGroupDto;
import java.util.Map;
import com.eshop.modules.user.vo.UserQueryVo;
import com.eshop.modules.activity.vo.StoreCouponUserVo;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.function.Function;
import java.math.BigDecimal;
import com.eshop.modules.cart.vo.StoreCartQueryVo;
import java.util.List;
import com.eshop.enums.ShopCommonEnum;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.eshop.modules.user.domain.UserAddress;
import java.io.Serializable;
import com.eshop.modules.cart.domain.StoreCart;
import com.eshop.modules.order.service.dto.OtherDto;
import com.eshop.api.EshopException;
import cn.hutool.core.util.ObjectUtil;
import com.eshop.modules.order.vo.ConfirmOrderVo;
import com.eshop.modules.user.domain.ShopUser;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.RedisTemplate;
import com.eshop.utils.RedisUtils;
import com.eshop.modules.cart.service.mapper.StoreCartMapper;
import com.eshop.modules.user.service.UserLevelService;
import com.eshop.modules.shop.service.SystemConfigService;
import com.eshop.modules.template.service.ShippingTemplatesFreeService;
import com.eshop.modules.template.service.ShippingTemplatesRegionService;
import com.eshop.modules.template.service.ShippingTemplatesService;
import com.eshop.modules.shop.service.SystemStoreStaffService;
import com.eshop.modules.cart.service.StoreCartService;
import com.eshop.modules.product.service.StoreProductReplyService;
import com.eshop.modules.shop.service.SystemStoreService;
import com.eshop.tools.service.AlipayConfigService;
import com.eshop.modules.order.service.ExpressService;
import com.eshop.modules.activity.service.StoreBargainService;
import com.eshop.modules.activity.service.StoreBargainUserService;
import com.eshop.modules.product.service.StoreProductService;
import com.eshop.modules.user.service.UserService;
import com.eshop.modules.activity.service.StoreCouponUserService;
import com.eshop.modules.user.service.UserBillService;
import com.eshop.modules.order.service.StoreOrderStatusService;
import com.eshop.modules.user.service.UserAddressService;
import com.eshop.modules.order.service.StoreOrderCartInfoService;
import com.eshop.modules.activity.service.StorePinkService;
import org.springframework.beans.factory.annotation.Autowired;
import com.eshop.dozer.service.IGenerator;
import org.slf4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import com.eshop.modules.order.service.StoreOrderService;
import com.eshop.modules.order.domain.StoreOrder;
import com.eshop.modules.order.service.mapper.StoreOrderMapper;
import com.eshop.common.service.impl.BaseServiceImpl;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
public class StoreOrderServiceImpl extends BaseServiceImpl<StoreOrderMapper, StoreOrder> implements StoreOrderService
{
    private static final Logger log;
    @Autowired
    private IGenerator generator;
    @Autowired
    private StorePinkService storePinkService;
    @Autowired
    private StoreOrderCartInfoService storeOrderCartInfoService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private StoreOrderCartInfoService orderCartInfoService;
    @Autowired
    private StoreOrderStatusService orderStatusService;
    @Autowired
    private UserBillService billService;
    @Autowired
    private StoreCouponUserService couponUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private StoreProductService productService;
    @Autowired
    private StorePinkService pinkService;
    @Autowired
    private StoreBargainUserService storeBargainUserService;
    @Autowired
    private StoreBargainService storeBargainService;
    @Autowired
    private ExpressService expressService;
    @Autowired
    private AlipayConfigService alipayService;
    @Autowired
    private SystemStoreService systemStoreService;
    @Autowired
    private StoreProductReplyService productReplyService;
    @Autowired
    private StoreCartService storeCartService;
    @Autowired
    private SystemStoreStaffService systemStoreStaffService;
    @Autowired
    private ShippingTemplatesService shippingTemplatesService;
    @Autowired
    private ShippingTemplatesRegionService shippingTemplatesRegionService;
    @Autowired
    private ShippingTemplatesFreeService shippingTemplatesFreeService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private UserLevelService userLevelService;
    @Autowired
    private StoreOrderMapper yxStoreOrderMapper;
    @Autowired
    private StoreCartMapper storeCartMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ApplicationEventPublisher publisher;
    
    public ConfirmOrderVo confirmOrder(final ShopUser shopUser, final String cartIds) {
        final Long uid = shopUser.getUid();
        //获取出valid和invalid的购物车商品
        final Map<String, Object> cartGroup = this.storeCartService.getUserProductCartList(uid, cartIds, 1);
        if (ObjectUtil.isNotEmpty(cartGroup.get("invalid"))) {
            throw new EshopException("有失效的商品请重新提交");
        }
        if (ObjectUtil.isEmpty(cartGroup.get("valid"))) {
            throw new EshopException("请提交购买的商品");
        }
        final OtherDto other = new OtherDto();
        //获取出积分开关是否打开
        other.setIntegralRatio(this.systemConfigService.getData("integral_ratio"));
        //满多少钱才能使用积分
        other.setIntegralFull(this.systemConfigService.getData("integral_full"));
        //使用积分的最大值
        other.setIntegralMax(this.systemConfigService.getData("integral_max"));
        Long combinationId = null;
        Long secKillId = null;
        Long bargainId = null;
        //如果前端传过来的购物车商品只有一个
        if (cartIds.split(",").length == 1) {
            //直接查询store_cart表，看该商品是拼团还是秒杀或者砍价
            final StoreCart cartQueryVo = (StoreCart)this.storeCartService.getById((Serializable)cartIds);
            combinationId = cartQueryVo.getCombinationId();
            secKillId = cartQueryVo.getSeckillId();
            bargainId = cartQueryVo.getBargainId();
        }
        //deduction的意思有扣除，推导，演绎
        boolean deduction = false;
        //默认允许使用积分
        boolean enableIntegral = true;
        //如果如果前端传过来的购物车商品只有一个，且是有效拼团/秒杀/砍价商品
        if ((combinationId != null && combinationId > 0L) || (secKillId != null && secKillId > 0L) || (bargainId != null && bargainId > 0L)) {
            //设置deduction为true，要传给前端的
            deduction = true;
        }
        //获取当前用户的默认地址
        final UserAddress userAddress = (UserAddress)this.userAddressService.getOne((Wrappers.<UserAddress>lambdaQuery().eq(UserAddress::getUid, uid)).eq(UserAddress::getIsDefault, ShopCommonEnum.DEFAULT_1.getValue()), false);
        //获取出valid购物车商品集合
        final List<StoreCartQueryVo> cartInfo = (List<StoreCartQueryVo>) cartGroup.get("valid");
        //根据valid购物车集合和默认地址计算出价格组
        //购物车总价格，购物车总成本，购物车总邮费，购物车总vip价格，购物车总需要的积分
        final PriceGroupDto priceGroup = this.getOrderPriceGroup(cartInfo, userAddress);
        //如果购物车总价格小于至少使用的积分数，那就不能使用积分
        if (priceGroup.getTotalPrice().compareTo(new BigDecimal(other.getIntegralFull())) < 0) {
            enableIntegral = false;
        }
        //将uid拼接其他的作为key，valid集合，价格组，other拼接成value，存到redis里面
        final String cacheKey = this.cacheOrderInfo(uid, cartInfo, priceGroup, other);
        //将productId取出来
        final List<String> productIds = cartInfo.stream().map(StoreCartQueryVo::getProductId).map(Object::toString).collect(Collectors.toList());
        //获取出优惠券
        final List<StoreCouponUserVo> storeCouponUsers = this.couponUserService.getUsableCouponList(uid, priceGroup.getTotalPrice().doubleValue(), productIds);
        StoreCouponUserVo storeCouponUser = null;
        //如果获取出来的优惠券列表不为空，则取出第一个优惠力度最大的优惠券作为默认使用优惠券
        if (storeCouponUsers != null && !storeCouponUsers.isEmpty()) {
            storeCouponUser = storeCouponUsers.get(0);
        }
        return ConfirmOrderVo.builder().addressInfo(userAddress).cartInfo(cartInfo).priceGroup(priceGroup).userInfo((UserQueryVo)this.generator.convert(shopUser, (Class)UserQueryVo.class)).orderKey(cacheKey).deduction(deduction).enableIntegral(enableIntegral).enableIntegralNum(Double.valueOf(other.getIntegralMax())).usableCoupon(storeCouponUser).systemStore(this.systemStoreService.getStoreInfo("", "")).build();
    }

    //计算订单价格
    public ComputeVo computedOrder(final ShopUser userInfo, final String key, String couponId, String useIntegral, final String shippingType, final String addressId) {
        final Long uid = userInfo.getUid();
        //查询redis里面的订单信息
        final CacheDto cacheDTO = this.getCacheOrderInfo(uid, key);
        //如果说没查到那就是订单过期了
        if (ObjectUtil.isNull(cacheDTO)) {
            throw new EshopException("订单已过期,请刷新当前页面");
        }
        //获取缓存中算出来的总的需要支付的价格
        BigDecimal payPrice = cacheDTO.getPriceGroup().getTotalPrice();
        UserAddress userAddress = null;
        //如果addressId不为空
        if (StrUtil.isNotBlank((CharSequence)addressId)) {
            //就通过addressId查询对应的地址信息
            userAddress = (UserAddress)this.userAddressService.getById((Serializable)addressId);
        }
        //又重新计算价格组，总价格，vip价格，成本价，总需要的积分，总运费等等
        final PriceGroupDto priceGroup = this.getOrderPriceGroup(cacheDTO.getCartInfo(), userAddress);
        //获取出总运费
        BigDecimal payPostage = priceGroup.getStorePostage();
        final Integer shippingTypeI = Integer.valueOf(shippingType);
        //配送方式如果是快递
        if (OrderInfoEnum.SHIPPIING_TYPE_1.getValue().equals(shippingTypeI)) {
            //就让支付价格等于商品总价，加运费
            payPrice = NumberUtil.add((Number)payPrice, (Number)payPostage);
        }
        else {
            //否则运费就是0，因为自提不需要运费
            payPostage = BigDecimal.ZERO;
        }
        Long combinationId = null;
        Long seckillId = null;
        Long bargainId = null;
        //从缓存中获取出购物车中的信息
        final List<StoreCartQueryVo> cartInfo = cacheDTO.getCartInfo();
        //因为拼团砍价和
        for (final StoreCartQueryVo cart : cartInfo) {
            combinationId = cart.getCombinationId();
            seckillId = cart.getSeckillId();
            bargainId = cart.getBargainId();
        }
        //如果发现购物车里面的商品有拼团，秒杀，砍价的，就不允许用优惠券或者积分
        if ((combinationId != null && combinationId > 0L) || (seckillId != null && seckillId > 0L) || (bargainId != null && bargainId > 0L)) {
            couponId = "";
            useIntegral = "";
        }
        //优惠券价格
        BigDecimal couponPrice = BigDecimal.ZERO;
        //如果countId不为空且有效
        if (StrUtil.isNotBlank((CharSequence)couponId) && !"0".equals(couponId)) {
            //根据countId去store_coupon_user表中查询该优惠券
            final StoreCouponUser couponUser = this.couponUserService.getCoupon(Integer.valueOf(couponId), uid);
            if (couponUser == null) {
                throw new EshopException("使用优惠劵失败");
            }
            if (couponUser.getUseMinPrice().compareTo(payPrice) > 0) {
                throw new EshopException("不满足优惠劵的使用条件");
            }
            //能用优惠券的话，更新下需要支付的金额以及优惠券的金额
            payPrice = NumberUtil.sub((Number)payPrice, (Number)couponUser.getCouponPrice());
            couponPrice = couponUser.getCouponPrice();
        }
        //所用的积分实际对应的价格
        BigDecimal deductionPrice = BigDecimal.ZERO;
        double usedIntegral = 0.0;
        //如果允许使用，且用户指定使用积分，且用户积分大于0
        if (StrUtil.isNotBlank((CharSequence)useIntegral) && "1".equals(useIntegral) && userInfo.getIntegral().intValue() > 0) {
            //最多能使用的积分
            final Double integralMax = Double.valueOf(cacheDTO.getOther().getIntegralMax());
            //
            final BigDecimal integralFull = new BigDecimal(cacheDTO.getOther().getIntegralFull());
            //是否能使用积分？
            final Double integralRatio = Double.valueOf(cacheDTO.getOther().getIntegralRatio());
            //如果当前商品总价格已经>=integralFull
            if (cacheDTO.getPriceGroup().getTotalPrice().compareTo(integralFull) >= 0) {
                //获取出当前用户所有的积分
                Double userIntegral = userInfo.getIntegral().doubleValue();
                //如果最多能使用的积分>0，且用户所拥有的积分比最多能使用的积分多
                if (integralMax.intValue() > 0 && Double.compare(userIntegral, integralMax) >= 0) {
                    //那直接设置userIntegral为最多能使用的积分
                    userIntegral = integralMax;
                }
                //integralRatio就是是否能使用积分的意思，如果为0就是不能使用积分，自然deductionPrice为0
                deductionPrice = BigDecimal.valueOf(NumberUtil.mul(userIntegral, integralRatio));
                //如果积分能兑换的价格小于要支付的价格，就让积分抵扣一些钱
                if (deductionPrice.compareTo(payPrice) < 0) {
                    payPrice = NumberUtil.sub((Number)payPrice, (Number)deductionPrice);
                    //记录用户使用了多少积分
                    usedIntegral = userIntegral;
                }
                //否则全部用积分就行了
                else {
                    //要消费多少钱就等于要消费多少积分，所以deductionPrice重新赋值
                    deductionPrice = payPrice;
                    //要支付的价格全部被积分抵消，为0
                    payPrice = BigDecimal.ZERO;
                    //使用的积分，这里如果integralRatio为0的话。。感觉这里有点问题啊
                    usedIntegral = NumberUtil.round(NumberUtil.div((Number)deductionPrice, (Number)BigDecimal.valueOf(integralRatio)), 2).doubleValue();
                }
            }
        }
        //如果查询出要支付的价格<=0，就直接置价格为0
        if (payPrice.compareTo(BigDecimal.ZERO) <= 0) {
            payPrice = BigDecimal.ZERO;
        }
        //构建ComputeVo
        return ComputeVo.builder().totalPrice(cacheDTO.getPriceGroup().getTotalPrice()).payPrice(payPrice).payPostage(payPostage).couponPrice(couponPrice).deductionPrice(deductionPrice).usedIntegral(usedIntegral).payIntegral(cacheDTO.getPriceGroup().getPayIntegral()).build();
    }

    //这个注解是用来自动清理缓存的
    //allEntries为true的属性，代表删除当前yshop:index_data的所有缓存
    @CacheEvict(cacheNames = { "yshop:index_data" }, allEntries = true)
    public StoreOrder createOrder(final ShopUser userInfo, final String key, final OrderParam param) {
        //计算订单价格
        final ComputeVo computeVo = this.computedOrder(userInfo, key, param.getCouponId(), param.getUseIntegral(), param.getShippingType(), param.getAddressId());
        final Long uid = userInfo.getUid();
        UserAddress userAddress = null;
        //如果该订单是快递配送
        if (OrderInfoEnum.SHIPPIING_TYPE_1.getValue().equals(Integer.valueOf(param.getShippingType()))) {
            //判空addressId
            if (StrUtil.isEmpty((CharSequence)param.getAddressId())) {
                throw new EshopException("请选择收货地址");
            }
            //根据addressId查询address
            userAddress = (UserAddress)this.userAddressService.getById((Serializable)param.getAddressId());
            if (ObjectUtil.isNull(userAddress)) {
                throw new EshopException("地址选择有误");
            }
        }
        else {
            //自提的话，前端必须传姓名和电话，快递之所以不用传，是因为用户事先存下了地址
            if (StrUtil.isBlank((CharSequence)param.getRealName()) || StrUtil.isBlank((CharSequence)param.getPhone())) {
                throw new EshopException("请填写姓名和电话");
            }
            userAddress = new UserAddress();
            userAddress.setRealName(param.getRealName());
            userAddress.setPhone(param.getPhone());
            userAddress.setProvince("");
            userAddress.setCity("");
            userAddress.setDistrict("");
            userAddress.setDetail("");
        }
        //购物车中商品总数量
        Integer totalNum = 0;
        final List<String> cartIds = new ArrayList<String>();
        Long combinationId = 0L;
        Long seckillId = 0L;
        Long bargainId = 0L;
        //默认不使用积分支付
        Boolean isIntegral = false;
        //使用积分数
        BigDecimal integral = BigDecimal.ZERO;
        //获取缓存中的订单信息
        final CacheDto cacheDTO = this.getCacheOrderInfo(uid, key);
        //获取订单列表
        final List<StoreCartQueryVo> cartInfo = cacheDTO.getCartInfo();
        for (final StoreCartQueryVo cart : cartInfo) {
            //检查库存
            this.storeCartService.checkProductStock(uid, cart.getProductId(), cart.getCartNum(), cart.getProductAttrUnique(), cart.getCombinationId(), cart.getSeckillId(), cart.getBargainId());
            combinationId = cart.getCombinationId();
            seckillId = cart.getSeckillId();
            bargainId = cart.getBargainId();
            //填入cartIds集合
            cartIds.add(cart.getId().toString());
            //累加商品数
            totalNum += cart.getCartNum();
            //如果该商品允许使用积分
            if (cart.getProductInfo().getIsIntegral() != null && cart.getProductInfo().getIsIntegral() == 1) {
                //积分也进行累加
                integral = NumberUtil.add((Number)integral, (Number)NumberUtil.mul((Number)cart.getCartNum(), (Number)cart.getProductInfo().getAttrInfo().getIntegral()));
            }
        }
        //可以获取的积分
        BigDecimal gainIntegral = this.getGainIntegral(cartInfo);
        //如果支付方式是用的积分，那么该订单支付后不会获取任何积分奖励
        if (PayTypeEnum.INTEGRAL.getValue().equals(param.getPayType())) {
            gainIntegral = BigDecimal.ZERO;
            //同时开启积分支付
            isIntegral = true;
        }
        //生成唯一的订单ID
        final String orderSn = IdUtil.getSnowflake(0L, 0L).nextIdStr();
        final StoreOrder storeOrder = new StoreOrder();
        //给storeOrder赋值
        storeOrder.setUid(Long.valueOf(String.valueOf(uid)));
        storeOrder.setOrderId(orderSn);
        storeOrder.setRealName(userAddress.getRealName());
        storeOrder.setUserPhone(userAddress.getPhone());
        storeOrder.setUserAddress(userAddress.getProvince() + " " + userAddress.getCity() + " " + userAddress.getDistrict() + " " + userAddress.getDetail());
        //设置CartId，但是要用Hutool工具类将Object数组转成用 , 分割的字符串，所以这里要先放到Object数组里面
        storeOrder.setCartId(StrUtil.join((CharSequence)",", new Object[] { cartIds }));
        storeOrder.setTotalNum(totalNum);
        storeOrder.setTotalPrice(computeVo.getTotalPrice());
        storeOrder.setTotalPostage(computeVo.getPayPostage());
        storeOrder.setCouponId(Integer.valueOf(param.getCouponId()));
        storeOrder.setCouponPrice(computeVo.getCouponPrice());
        storeOrder.setPayPrice(computeVo.getPayPrice());
        storeOrder.setPayPostage(computeVo.getPayPostage());
        storeOrder.setDeductionPrice(computeVo.getDeductionPrice());
        //暂时还是未支付状态
        storeOrder.setPaid(OrderInfoEnum.PAY_STATUS_0.getValue());
        storeOrder.setPayType(param.getPayType());
        //用户支付是否使用的积分
        if (isIntegral) {
            storeOrder.setPayIntegral(integral);
        }
        //设置用了多少积分
        storeOrder.setUseIntegral(BigDecimal.valueOf(computeVo.getUsedIntegral()));
        //给用户退了多少积分
        storeOrder.setBackIntegral(BigDecimal.ZERO);
        //消费赚取积分
        storeOrder.setGainIntegral(gainIntegral);
        storeOrder.setMark(param.getMark());
        storeOrder.setCombinationId(combinationId);
        storeOrder.setPinkId(Long.valueOf(param.getPinkId()));
        storeOrder.setSeckillId(seckillId);
        storeOrder.setBargainId(bargainId);
        //总的成本价
        storeOrder.setCost(cacheDTO.getPriceGroup().getCostPrice());
        if (AppFromEnum.ROUNTINE.getValue().equals(param.getFrom())) {
            //小程序支付渠道
            storeOrder.setIsChannel(OrderInfoEnum.PAY_CHANNEL_1.getValue());
        }
        else {
            //公众号/H5支付渠道
            storeOrder.setIsChannel(OrderInfoEnum.PAY_CHANNEL_0.getValue());
        }
        storeOrder.setUnique(key);
        //配送方式
        storeOrder.setShippingType(Integer.valueOf(param.getShippingType()));
        //如果配送方式是门店自提
        if (OrderInfoEnum.SHIPPIING_TYPE_2.getValue().toString().equals(param.getShippingType())) {
            //查询system_store表，根据store_id
            final SystemStore systemStoreQueryVo = (SystemStore)this.systemStoreService.getById((Serializable)param.getStoreId());
            //如果没有就说明没有门店可提供自提
            if (systemStoreQueryVo == null) {
                throw new ErrorRequestException("暂无门店无法选择门店自提");
            }
            //设置核销码 直接就是截取的orderSn，从尾部开始往前算12个格子，然后从这里一直截取到末尾
            //具体使用已经记录到笔记中了，这个工具类还是比较奇怪
            storeOrder.setVerifyCode(StrUtil.sub((CharSequence)orderSn, orderSn.length(), -12));
            //设置店铺ID
            storeOrder.setStoreId(systemStoreQueryVo.getId());
        }
        //直接保存订单到数据库 store_order
        final boolean res = this.save(storeOrder);
        if (!res) {
            throw new EshopException("订单生成失败");
        }
        //如果使用的积分>0
        if (computeVo.getUsedIntegral() > 0.0) {
            //DeductionPrice是抵扣的价格
            this.decIntegral(userInfo, computeVo.getUsedIntegral(), computeVo.getDeductionPrice().doubleValue());
        }
        //如果使用了优惠券后累加优惠券的价格>0，就将该优惠券标记为使用，并记录使用时间
        //具体操作的是store_coupon_user表，执行修改操作
        if (computeVo.getCouponPrice().compareTo(BigDecimal.ZERO) > 0) {
            this.couponUserService.useCoupon(Integer.valueOf(param.getCouponId()));
        }
        this.deStockIncSale(cartInfo);
        //保存订单具体信息，其中会将产品信息以json形式保存到表中
        //具体操作的是store_order_cart_info表，注意是多条记录，有多少个购物车商品就添加几条数据
        //每个购物车商品的cartId都不一样，并不是一堆商品共用一个购物车ID，这个一定要想清楚
        this.orderCartInfoService.saveCartInfo(storeOrder.getId(), cartInfo);
        final StoreCart cartObj = new StoreCart();
        //设置成已支付
        cartObj.setIsPay(OrderInfoEnum.PAY_STATUS_1.getValue());
        //把cartId对应的订单们全部设置成已支付，因此这里使用的是In关键字
        this.storeCartMapper.update(cartObj, Wrappers.<StoreCart>lambdaQuery().in(StoreCart::getId, cartIds));
        //删除缓存订单
        this.delCacheOrderInfo(uid, key);
        //往store_order_status订单操作表里面保存该订单的数据    yshop_create_order               订单生成
        this.orderStatusService.create(storeOrder.getId(), OrderLogEnum.CREATE_ORDER.getValue(), OrderLogEnum.CREATE_ORDER.getDesc());
        //又构建一个等待支付的redis，时间是30分钟
        final String redisKey = String.valueOf(StrUtil.format((CharSequence)"{}{}", new Object[] { "order:unpay:", storeOrder.getId() }));
        this.redisTemplate.opsForValue().set(redisKey, storeOrder.getOrderId(), 30L, TimeUnit.MINUTES);
        return storeOrder;
    }
    
    public void orderComment(final ShopUser user, final String unique, final String comment, final String pics, final String productScore, final String serviceScore) {
        //根据unique，这个是store_order_cart_info中的唯一值，去查询订单商品
        final StoreOrderCartInfo orderCartInfo = (StoreOrderCartInfo)this.storeOrderCartInfoService
                .getOne(Wrappers.<StoreOrderCartInfo>lambdaQuery().eq(StoreOrderCartInfo::getUnique, unique));
        //判空
        if (ObjectUtil.isEmpty(orderCartInfo)) {
            throw new EshopException("评价产品不存在");
        }
        //根据Oid和ProductId去查store_product_reply表
        final int count = this.productReplyService.count((Wrappers.<StoreProductReply>lambdaQuery()
                .eq(StoreProductReply::getOid, orderCartInfo.getOid()))
                .eq(StoreProductReply::getProductId, orderCartInfo.getProductId()));
        //判断是否已经评论过该商品
        if (count > 0) {
            throw new EshopException("该产品已评价");
        }
        //构建商品评论对象
        final StoreProductReply storeProductReply = StoreProductReply.builder()
                .uid(user.getUid()).oid(orderCartInfo.getOid())
                .productId(orderCartInfo.getProductId())
                .productScore(Integer.valueOf(productScore))
                .serviceScore(Integer.valueOf(serviceScore)).comment(comment)
                .pics(pics).unique(unique).build();
        //直接保存到数据库
        this.productReplyService.save(storeProductReply);
        //获取该订单下所有的评论数
        final int replyCount = this.productReplyService.count(Wrappers.<StoreProductReply>lambdaQuery()
                .eq(StoreProductReply::getOid, orderCartInfo.getOid()));
        //获取该订单在store_order_cart_info表中，同一订单下所有商品的数量
        final int cartCount = this.storeOrderCartInfoService.count(Wrappers.<StoreOrderCartInfo>lambdaQuery()
                .eq(StoreOrderCartInfo::getOid, orderCartInfo.getOid()));
        //如果该订单下所有的评论数等于同一订单下所有商品的数量，那么该订单的状态直接改成已完成
        if (replyCount == cartCount) {
            final StoreOrder storeOrder = new StoreOrder();
            storeOrder.setStatus(OrderInfoEnum.STATUS_3.getValue());
            storeOrder.setId(orderCartInfo.getOid());
            this.yxStoreOrderMapper.updateById(storeOrder);
        }
        //保存数据到store_order_status（订单操作记录表）
        this.orderStatusService.create(orderCartInfo.getOid(), OrderLogEnum.EVAL_ORDER.getValue(), OrderLogEnum.EVAL_ORDER.getDesc());
    }
    
    public void orderRefund(final String orderId, final BigDecimal price, final Integer type) {
        final StoreOrderQueryVo orderQueryVo = this.getOrderInfo(orderId, null);
        if (ObjectUtil.isNull(orderQueryVo)) {
            throw new EshopException("订单不存在");
        }
        final UserQueryVo userQueryVo = this.userService.getYxUserById(orderQueryVo.getUid());
        if (ObjectUtil.isNull(userQueryVo)) {
            throw new EshopException("用户不存在");
        }
        if (OrderInfoEnum.REFUND_STATUS_2.getValue().equals(orderQueryVo.getRefundStatus())) {
            throw new EshopException("订单已经退款了哦！");
        }
        if (orderQueryVo.getPayPrice().compareTo(price) < 0) {
            throw new EshopException("退款金额不正确");
        }
        final StoreOrder storeOrder = new StoreOrder();
        storeOrder.setId(orderQueryVo.getId());
        if (ShopCommonEnum.AGREE_2.getValue().equals(type)) {
            storeOrder.setRefundStatus(OrderInfoEnum.REFUND_STATUS_0.getValue());
            this.yxStoreOrderMapper.updateById(storeOrder);
            return;
        }
        if (PayTypeEnum.YUE.getValue().equals(orderQueryVo.getPayType())) {
            storeOrder.setRefundStatus(OrderInfoEnum.REFUND_STATUS_2.getValue());
            storeOrder.setRefundPrice(price);
            this.yxStoreOrderMapper.updateById(storeOrder);
            this.userService.incMoney(orderQueryVo.getUid(), price);
            this.billService.income(orderQueryVo.getUid(), "商品退款", BillDetailEnum.CATEGORY_1.getValue(), BillDetailEnum.TYPE_5.getValue(), price.doubleValue(), NumberUtil.add((Number)price, (Number)userQueryVo.getNowMoney()).doubleValue(), "订单退款到余额" + price + "元", orderQueryVo.getId().toString());
            this.retrunStock(orderQueryVo.getOrderId());
        }
        else if (PayTypeEnum.INTEGRAL.getValue().equals(orderQueryVo.getPayType())) {
            storeOrder.setRefundStatus(OrderInfoEnum.REFUND_STATUS_2.getValue());
            storeOrder.setRefundPrice(price);
            this.yxStoreOrderMapper.updateById(storeOrder);
            this.orderStatusService.create(orderQueryVo.getId(), OrderLogEnum.ORDER_EDIT.getValue(), "退款给用户：" + orderQueryVo.getPayIntegral() + "分");
            this.retrunStock(orderQueryVo.getOrderId());
        }
        this.orderStatusService.create(orderQueryVo.getId(), OrderLogEnum.REFUND_ORDER_SUCCESS.getValue(), "退款给用户：" + price + "元");
        final TemplateBean templateBean = TemplateBean.builder().orderId(orderQueryVo.getOrderId()).price(orderQueryVo.getPayPrice().toString()).uid(orderQueryVo.getUid()).templateType(TemplateListenEnum.TYPE_2.getValue()).time(DateUtil.formatTime(new Date())).payType(orderQueryVo.getPayType()).build();
        this.publisher.publishEvent((ApplicationEvent)new TemplateEvent(this, templateBean));
    }
    
    public void orderDelivery(final String orderId, final String deliveryId, final String deliveryName, final String deliveryType) {
        final StoreOrderQueryVo orderQueryVo = this.getOrderInfo(orderId, null);
        if (ObjectUtil.isNull(orderQueryVo)) {
            throw new EshopException("订单不存在");
        }
        if (!OrderInfoEnum.STATUS_0.getValue().equals(orderQueryVo.getStatus()) || OrderInfoEnum.PAY_STATUS_0.getValue().equals(orderQueryVo.getPaid())) {
            throw new EshopException("订单状态错误");
        }
        final EshopExpress expressQueryVo = (EshopExpress)this.expressService.getOne(Wrappers.<EshopExpress>lambdaQuery().eq(EshopExpress::getName, deliveryName));
        if (ObjectUtil.isNull(expressQueryVo)) {
            throw new EshopException("请后台先添加快递公司");
        }
        if (orderQueryVo.getPinkId() != null && orderQueryVo.getPinkId() > 0L) {
            final StorePink pink = (StorePink)this.pinkService.getById((Serializable)orderQueryVo.getPinkId());
            if (!OrderInfoEnum.PINK_STATUS_2.getValue().equals(pink.getStatus())) {
                throw new EshopException("拼团未成功不能发货");
            }
        }
        final StoreOrder storeOrder = StoreOrder.builder().id(orderQueryVo.getId()).status(OrderInfoEnum.STATUS_1.getValue()).deliveryId(deliveryId).deliveryName(expressQueryVo.getName()).deliveryType(deliveryType).deliverySn(expressQueryVo.getCode()).build();
        this.yxStoreOrderMapper.updateById(storeOrder);
        this.orderStatusService.create(orderQueryVo.getId(), OrderLogEnum.DELIVERY_GOODS.getValue(), "已发货 快递公司：" + expressQueryVo.getName() + "快递单号：" + deliveryId);
        final TemplateBean templateBean = TemplateBean.builder().orderId(orderQueryVo.getOrderId()).deliveryId(deliveryId).deliveryName(expressQueryVo.getName()).uid(orderQueryVo.getUid()).templateType(TemplateListenEnum.TYPE_3.getValue()).build();
        this.publisher.publishEvent((ApplicationEvent)new TemplateEvent(this, templateBean));
        final String redisKey = String.valueOf(StrUtil.format((CharSequence)"{}{}", new Object[] { "order:unconfirm:", orderQueryVo.getId() }));
        this.redisTemplate.opsForValue().set(redisKey, orderQueryVo.getOrderId(), 7L, TimeUnit.DAYS);
    }
    
    public void updateDelivery(final String orderId, final String deliveryId, final String deliveryName, final String deliveryType) {
        final StoreOrderQueryVo orderQueryVo = this.getOrderInfo(orderId, null);
        if (ObjectUtil.isNull(orderQueryVo)) {
            throw new EshopException("订单不存在");
        }
        if (!OrderInfoEnum.STATUS_1.getValue().equals(orderQueryVo.getStatus()) || OrderInfoEnum.PAY_STATUS_0.getValue().equals(orderQueryVo.getPaid())) {
            throw new EshopException("订单状态错误");
        }
        final EshopExpress expressQueryVo = (EshopExpress)this.expressService.getOne(Wrappers.<EshopExpress>lambdaQuery().eq(EshopExpress::getName, deliveryName));
        if (ObjectUtil.isNull(expressQueryVo)) {
            throw new EshopException("请后台先添加快递公司");
        }
        final StoreOrder storeOrder = StoreOrder.builder().id(orderQueryVo.getId()).deliveryId(deliveryId).deliveryName(expressQueryVo.getName()).deliveryType(deliveryType).deliverySn(expressQueryVo.getCode()).build();
        this.yxStoreOrderMapper.updateById(storeOrder);
    }
    
    public void editOrderPrice(final String orderId, final String price) {
        final StoreOrderQueryVo orderQueryVo = this.getOrderInfo(orderId, null);
        if (ObjectUtil.isNull(orderQueryVo)) {
            throw new EshopException("订单不存在");
        }
        if (orderQueryVo.getPayPrice().compareTo(new BigDecimal(price)) == 0) {
            return;
        }
        if (OrderInfoEnum.PAY_STATUS_1.getValue().equals(orderQueryVo.getPaid())) {
            throw new EshopException("订单状态错误");
        }
        final StoreOrder storeOrder = new StoreOrder();
        storeOrder.setId(orderQueryVo.getId());
        storeOrder.setPayPrice(new BigDecimal(price));
        if (orderQueryVo.getPayPrice().compareTo(new BigDecimal(price)) != 0) {
            final String orderSn = IdUtil.getSnowflake(0L, 0L).nextIdStr();
            storeOrder.setExtendOrderId(orderSn);
        }
        this.yxStoreOrderMapper.updateById(storeOrder);
        this.orderStatusService.create(storeOrder.getId(), OrderLogEnum.ORDER_EDIT.getValue(), "修改实际支付金额");
    }
    
    public StoreOrder getOrderPink(final Long pid, final Long uid) {
        return (((this.lambdaQuery().eq(StoreOrder::getUid, uid)).eq(StoreOrder::getPinkId, pid)).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).one();
    }
    
    public void cancelOrder(final String orderId, final Long uid) {
        final StoreOrderQueryVo order = this.getOrderInfo(orderId, uid);
        if (ObjectUtil.isNull(order)) {
            throw new EshopException("订单不存在");
        }
        this.regressionIntegral(order, 0);
        this.regressionStock(order, 0);
        this.regressionCoupon(order, 0);
        this.yxStoreOrderMapper.deleteById((Serializable)order.getId());
    }
    
    public void removeOrder(final String orderId, final Long uid) {
        StoreOrderQueryVo order = this.getOrderInfo(orderId, (long)uid);
        if (order == null) {
            throw new EshopException("订单不存在");
        }
        order = this.handleOrder(order);
        if (!OrderInfoEnum.STATUS_3.getValue().equals(order.getStatus())) {
            throw new EshopException("该订单无法删除");
        }
        this.yxStoreOrderMapper.deleteById((Serializable)order.getId());
        this.orderStatusService.create(order.getId(), OrderLogEnum.REMOVE_ORDER.getValue(), OrderLogEnum.REMOVE_ORDER.getDesc());
    }
    
    @CacheEvict(cacheNames = { "yshop:index_data" }, allEntries = true)
    public void takeOrder(final String orderId, final Long uid) {
        StoreOrderQueryVo order = this.getOrderInfo(orderId, uid);
        if (ObjectUtil.isNull(order)) {
            throw new EshopException("订单不存在");
        }
        order = this.handleOrder(order);
        if (!OrderStatusEnum.STATUS_2.getValue().toString().equals(order.getStatusDto().getType())) {
            throw new BusinessException("订单状态错误");
        }
        final StoreOrder storeOrder = new StoreOrder();
        storeOrder.setStatus(OrderInfoEnum.STATUS_2.getValue());
        storeOrder.setId(order.getId());
        this.yxStoreOrderMapper.updateById(storeOrder);
        this.orderStatusService.create(order.getId(), OrderLogEnum.TAKE_ORDER_DELIVERY.getValue(), OrderLogEnum.TAKE_ORDER_DELIVERY.getDesc());
        this.gainUserIntegral(order);
        this.userService.backOrderBrokerage(order);
    }
    
    public StoreOrderQueryVo verifyOrder(final String verifyCode, final Integer isConfirm, final Long uid) {
        final StoreOrder order = (StoreOrder)this.getOne(((Wrappers.<StoreOrder>lambdaQuery().eq(StoreOrder::getVerifyCode, verifyCode)).eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue()));
        if (order == null) {
            throw new EshopException("核销的订单不存在或未支付或已退款");
        }
        if (uid != null) {
            final boolean checkStatus = this.systemStoreStaffService.checkStatus(uid, order.getStoreId());
            if (!checkStatus) {
                throw new EshopException("您没有当前店铺核销权限");
            }
        }
        if (!OrderInfoEnum.STATUS_0.getValue().equals(order.getStatus())) {
            throw new EshopException("订单已经核销");
        }
        if (order.getCombinationId() != null && order.getCombinationId() > 0L && order.getPinkId() != null && order.getPinkId() > 0L) {
            final StorePink storePink = (StorePink)this.storePinkService.getById((Serializable)order.getPinkId());
            if (!OrderInfoEnum.PINK_STATUS_2.getValue().equals(storePink.getStatus())) {
                throw new EshopException("拼团订单暂未成功无法核销");
            }
        }
        final StoreOrderQueryVo orderQueryVo = (StoreOrderQueryVo)this.generator.convert(order, (Class)StoreOrderQueryVo.class);
        if (OrderInfoEnum.CONFIRM_STATUS_0.getValue().equals(isConfirm)) {
            return orderQueryVo;
        }
        final StoreOrder storeOrder = new StoreOrder();
        storeOrder.setStatus(OrderInfoEnum.STATUS_2.getValue());
        storeOrder.setId(order.getId());
        this.yxStoreOrderMapper.updateById(storeOrder);
        this.orderStatusService.create(order.getId(), OrderLogEnum.TAKE_ORDER_DELIVERY.getValue(), "已核销");
        this.gainUserIntegral(orderQueryVo);
        this.userService.backOrderBrokerage(orderQueryVo);
        this.userLevelService.setLevelComplete(order.getUid());
        return null;
    }
    
    public void orderApplyRefund(final String explain, final String Img, final String text, final String orderId, final Long uid) {
        final StoreOrderQueryVo order = this.getOrderInfo(orderId, uid);
        if (order == null) {
            throw new EshopException("订单不存在");
        }
        if (OrderInfoEnum.REFUND_STATUS_2.getValue().equals(order.getRefundStatus())) {
            throw new EshopException("订单已退款");
        }
        if (OrderInfoEnum.REFUND_STATUS_1.getValue().equals(order.getRefundStatus())) {
            throw new EshopException("正在申请退款中");
        }
        if (OrderInfoEnum.STATUS_1.getValue().equals(order.getStatus())) {
            throw new EshopException("订单当前无法退款");
        }
        final StoreOrder storeOrder = new StoreOrder();
        storeOrder.setRefundStatus(OrderInfoEnum.REFUND_STATUS_1.getValue());
        storeOrder.setRefundReasonTime(new Date());
        storeOrder.setRefundReasonWapExplain(explain);
        storeOrder.setRefundReasonWapImg(Img);
        storeOrder.setRefundReasonWap(text);
        storeOrder.setId(order.getId());
        this.yxStoreOrderMapper.updateById(storeOrder);
        this.orderStatusService.create(order.getId(), OrderLogEnum.REFUND_ORDER_APPLY.getValue(), "用户申请退款，原因：" + text);
        final TemplateBean templateBean = TemplateBean.builder().orderId(order.getOrderId()).price(order.getPayPrice().toString()).uid(order.getUid()).templateType(TemplateListenEnum.TYPE_9.getValue()).time(DateUtil.formatTime(new Date())).build();
        this.publisher.publishEvent((ApplicationEvent)new TemplateEvent(this, templateBean));
    }
    
    public List<StoreOrderQueryVo> orderList(final Long uid, final int type, final int page, final int limit) {
        final LambdaQueryWrapper<StoreOrder> wrapper = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        if (uid != null) {
            wrapper.eq(StoreOrder::getUid, uid);
        }
        wrapper.orderByDesc(StoreOrder::getId);
        switch (OrderStatusEnum.toType(type)) {
            case STATUS_0: {
                ((wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_0.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_0.getValue());
                break;
            }
            case STATUS_1: {
                ((wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_0.getValue());
                break;
            }
            case STATUS_2: {
                ((wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_1.getValue());
                break;
            }
            case STATUS_3: {
                ((wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_2.getValue());
                break;
            }
            case STATUS_4: {
                ((wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_3.getValue());
                break;
            }
            case STATUS_MINUS_1: {
                (wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_1.getValue());
                break;
            }
            case STATUS_MINUS_2: {
                (wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_0.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_2.getValue());
                break;
            }
            case STATUS_MINUS_3: {
                final String[] strs = { "1", "2" };
                (wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).in(StoreOrder::getRefundStatus, (Collection)Arrays.asList(strs));
                break;
            }
        }
        final Page<StoreOrder> pageModel = (Page<StoreOrder>)new Page((long)page, (long)limit);
        final IPage<StoreOrder> pageList = (IPage<StoreOrder>)this.yxStoreOrderMapper.selectPage((IPage)pageModel, (Wrapper)wrapper);
        final List<StoreOrderQueryVo> list = (List<StoreOrderQueryVo>)this.generator.convert(pageList.getRecords(), (Class)StoreOrderQueryVo.class);
        return list.stream().map(this::handleOrder).collect(Collectors.toList());
    }
    
    public Map<String, Object> orderListByPage(final Long uid, final int type, final int page, final int limit) {
        final LambdaQueryWrapper<StoreOrder> wrapper = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        if (uid != null) {
            wrapper.eq(StoreOrder::getUid, uid);
        }
        wrapper.orderByDesc(StoreOrder::getId);
        //toType这个方法就是根据value值将其value转换成对应的枚举类
        switch (OrderStatusEnum.toType(type)) {
            case STATUS_0: {
                //未支付，正常未退款，订单默认状态
                ((wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_0.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_0.getValue());
                break;
            }
            case STATUS_1: {
                //已支付，正常未退款，订单默认状态
                ((wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_0.getValue());
                break;
            }
            case STATUS_2: {
                //已支付，正常未退款，订单待收货
                ((wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_1.getValue());
                break;
            }
            case STATUS_3: {
                //已支付，正常未退款，订单已收货
                ((wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_2.getValue());
                break;
            }
            case STATUS_4: {
                //已支付，正常未退款，订单已完成
                ((wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_3.getValue());
                break;
            }
            case STATUS_MINUS_1: {
                //已支付，退款中
                (wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_1.getValue());
                break;
            }
            case STATUS_MINUS_2: {
                //未支付，已退款
                (wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_0.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_2.getValue());
                break;
            }
            case STATUS_MINUS_3: {
                final String[] strs = { "1", "2" };
                //已支付， 订单状态是 申请中和已退款
                (wrapper.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).in(StoreOrder::getRefundStatus, (Collection)Arrays.asList(strs));
                break;
            }
        }
        //构建分页查询
        final Page<StoreOrder> pageModel = (Page<StoreOrder>)new Page((long)page, (long)limit);
        //查询结果
        final IPage<StoreOrder> pageList = (IPage<StoreOrder>)this.yxStoreOrderMapper.selectPage((IPage)pageModel, (Wrapper)wrapper);
        //取出原始数据，转化成vo对象，返回集合
        final List<StoreOrderQueryVo> list = (List<StoreOrderQueryVo>)this.generator.convert(pageList.getRecords(), (Class)StoreOrderQueryVo.class);
        //构建返回map
        final Map<String, Object> map = new LinkedHashMap<String, Object>(2);
        //将vo集合中的每个订单都进行处理，然后重新收集成一个集合
        map.put("content", list.stream().map(this::handleOrder).collect(Collectors.toList()));
        map.put("totalElements", pageList.getTotal());
        return map;
    }
    
    @Deprecated
    public ShoperOrderTimeDataVo getShoperOrderTimeData() {
        final Date today = (Date)DateUtil.beginOfDay(new Date());
        final Date yesterday = (Date)DateUtil.beginOfDay((Date)DateUtil.yesterday());
        final Date nowMonth = (Date)DateUtil.beginOfMonth(new Date());
        final Date lastWeek = (Date)DateUtil.beginOfDay((Date)DateUtil.lastWeek());
        final ShoperOrderTimeDataVo orderTimeDataVo = new ShoperOrderTimeDataVo();
        final LambdaQueryWrapper<StoreOrder> wrapperOne = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        ((wrapperOne.ge(StoreOrder::getPayTime, today)).eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue());
        orderTimeDataVo.setTodayPrice(this.yxStoreOrderMapper.todayPrice((Wrapper<StoreOrder>)wrapperOne));
        orderTimeDataVo.setTodayCount(this.yxStoreOrderMapper.selectCount((Wrapper)wrapperOne));
        final LambdaQueryWrapper<StoreOrder> wrapperTwo = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        (((wrapperTwo.lt(StoreOrder::getPayTime, today)).ge(StoreOrder::getPayTime, yesterday)).eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue());
        orderTimeDataVo.setProPrice(this.yxStoreOrderMapper.todayPrice((Wrapper<StoreOrder>)wrapperTwo));
        orderTimeDataVo.setProCount(this.yxStoreOrderMapper.selectCount((Wrapper)wrapperTwo));
        final LambdaQueryWrapper<StoreOrder> wrapperThree = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        ((wrapperThree.ge(StoreOrder::getPayTime, nowMonth)).eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue());
        orderTimeDataVo.setMonthPrice(this.yxStoreOrderMapper.todayPrice((Wrapper<StoreOrder>)wrapperThree));
        orderTimeDataVo.setMonthCount(this.yxStoreOrderMapper.selectCount((Wrapper)wrapperThree));
        final LambdaQueryWrapper<StoreOrder> wrapperLastWeek = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        (((wrapperLastWeek.lt(StoreOrder::getPayTime, today)).ge(StoreOrder::getPayTime, lastWeek)).eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue());
        orderTimeDataVo.setLastWeekPrice(this.yxStoreOrderMapper.todayPrice((Wrapper<StoreOrder>)wrapperLastWeek));
        orderTimeDataVo.setLastWeekCount(this.yxStoreOrderMapper.selectCount((Wrapper)wrapperLastWeek));
        return orderTimeDataVo;
    }
    
    public List<OrderDataVo> getOrderDataPriceCount(final int page, final int limit) {
        final Page<StoreOrder> pageModel = (Page<StoreOrder>)new Page((long)page, (long)limit);
        return this.yxStoreOrderMapper.getOrderDataPriceList(pageModel);
    }
    
    public UserOrderCountVo orderData(final Long uid) {
        final LambdaQueryWrapper<StoreOrder> wrapperOne = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        if (uid != null) {
            wrapperOne.eq(StoreOrder::getUid, uid);
        }
        (wrapperOne.eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue());
        final Integer orderCount = this.yxStoreOrderMapper.selectCount((Wrapper)wrapperOne);
        final double sumPrice = this.yxStoreOrderMapper.sumPrice(uid);
        final LambdaQueryWrapper<StoreOrder> wrapperTwo = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        if (uid != null) {
            wrapperTwo.eq(StoreOrder::getUid, uid);
        }
        ((wrapperTwo.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_0.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_0.getValue());
        final Integer unpaidCount = this.yxStoreOrderMapper.selectCount((Wrapper)wrapperTwo);
        final LambdaQueryWrapper<StoreOrder> wrapperThree = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        if (uid != null) {
            wrapperThree.eq(StoreOrder::getUid, uid);
        }
        ((wrapperThree.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_0.getValue());
        final Integer unshippedCount = this.yxStoreOrderMapper.selectCount((Wrapper)wrapperThree);
        final LambdaQueryWrapper<StoreOrder> wrapperFour = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        if (uid != null) {
            wrapperFour.eq(StoreOrder::getUid, uid);
        }
        ((wrapperFour.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_1.getValue());
        final Integer receivedCount = this.yxStoreOrderMapper.selectCount((Wrapper)wrapperFour);
        final LambdaQueryWrapper<StoreOrder> wrapperFive = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        if (uid != null) {
            wrapperFive.eq(StoreOrder::getUid, uid);
        }
        ((wrapperFive.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_2.getValue());
        final Integer evaluatedCount = this.yxStoreOrderMapper.selectCount((Wrapper)wrapperFive);
        final LambdaQueryWrapper<StoreOrder> wrapperSix = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        if (uid != null) {
            wrapperSix.eq(StoreOrder::getUid, uid);
        }
        ((wrapperSix.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).eq(StoreOrder::getRefundStatus, OrderInfoEnum.REFUND_STATUS_0.getValue())).eq(StoreOrder::getStatus, OrderInfoEnum.STATUS_3.getValue());
        final Integer completeCount = this.yxStoreOrderMapper.selectCount((Wrapper)wrapperSix);
        final LambdaQueryWrapper<StoreOrder> wrapperSeven = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        if (uid != null) {
            wrapperSeven.eq(StoreOrder::getUid, uid);
        }
        final String[] strArr = { "1", "2" };
        (wrapperSeven.eq(StoreOrder::getPaid, OrderInfoEnum.PAY_STATUS_1.getValue())).in(StoreOrder::getRefundStatus, (Collection)Arrays.asList(strArr));
        final Integer refundCount = this.yxStoreOrderMapper.selectCount((Wrapper)wrapperSeven);
        return UserOrderCountVo.builder().orderCount(orderCount).sumPrice(sumPrice).unpaidCount(unpaidCount).unshippedCount(unshippedCount).receivedCount(receivedCount).evaluatedCount(evaluatedCount).completeCount(completeCount).refundCount(refundCount).build();
    }

    //处理订单
    public StoreOrderQueryVo handleOrder(final StoreOrderQueryVo order) {
        final LambdaQueryWrapper<StoreOrderCartInfo> wrapper = (LambdaQueryWrapper<StoreOrderCartInfo>)new LambdaQueryWrapper();
        //条件拼接Oid
        wrapper.eq(StoreOrderCartInfo::getOid, order.getId());
        //查询出某个订单下所有的商品，OrderCartInfo
        final List<StoreOrderCartInfo> cartInfos = (List<StoreOrderCartInfo>)this.orderCartInfoService.list((Wrapper)wrapper);
        //将StoreOrderCartInfo转换成Vo对象
        final List<StoreCartQueryVo> cartInfo = cartInfos.stream().map(cart -> {
            StoreCartQueryVo cartQueryVo = (StoreCartQueryVo)JSON.parseObject(cart.getCartInfo(), (Class)StoreCartQueryVo.class);
            //有些属性需要手动设置
            cartQueryVo.setUnique(cart.getUnique());
            //因为这个商城的设定就是，一个商品只能评价一条，所以直接count查出数据就行了
            //有评论那最多也就是1，没评论就是0
            cartQueryVo.setIsReply(this.productReplyService.replyCount(cart.getUnique()));
            return cartQueryVo;
        }).collect(Collectors.toList());
        //设置OrderCartInfoVos
        order.setCartInfo(cartInfo);
        //构建StatusDto，根据情况设置属性
        final StatusDto statusDTO = new StatusDto();
        if (OrderStatusEnum.STATUS_0.getValue().equals(order.getPaid())) {
            //未支付订单，有三十分钟的时间可以自由选择支付或者不支付
            final int offset = Integer.valueOf(String.valueOf(30L));
            //通过工具类计算出从订单创建时间+偏移量的具体时间，也就是订单不可支付的时间点
            final Date time = (Date)DateUtil.offsetMinute(order.getCreateTime(), offset);
            statusDTO.setClassfy("nobuy");
            statusDTO.setMsg(StrUtil.format((CharSequence)"请在{}前完成支付", new Object[] { DateUtil.formatDateTime(time) }));
            statusDTO.setType("0");
            statusDTO.setTitle("未支付");
        }
        else if (OrderInfoEnum.REFUND_STATUS_1.getValue().equals(order.getRefundStatus())) {
            statusDTO.setClassfy("state-sqtk");
            statusDTO.setMsg("商家审核中,请耐心等待");
            statusDTO.setType("-1");
            statusDTO.setTitle("申请退款中");
        }
        else if (OrderInfoEnum.REFUND_STATUS_2.getValue().equals(order.getRefundStatus())) {
            statusDTO.setClassfy("state-sqtk");
            statusDTO.setMsg("已为您退款,感谢您的支持");
            statusDTO.setType("-2");
            statusDTO.setTitle("已退款");
        }
        else if (OrderInfoEnum.STATUS_0.getValue().equals(order.getStatus())) {
            if (order.getPinkId() > 0L) {
                if (this.pinkService.pinkIngCount(order.getPinkId()) > 0) {
                    statusDTO.setClassfy("state-nfh");
                    statusDTO.setMsg("待其他人参加拼团");
                    statusDTO.setType("1");
                    statusDTO.setTitle("拼团中");
                }
                else {
                    statusDTO.setClassfy("state-nfh");
                    statusDTO.setMsg("商家未发货,请耐心等待");
                    statusDTO.setType("1");
                    statusDTO.setTitle("未发货");
                }
            }
            else if (OrderInfoEnum.SHIPPIING_TYPE_1.getValue().equals(order.getShippingType())) {
                statusDTO.setClassfy("state-nfh");
                statusDTO.setMsg("商家未发货,请耐心等待");
                statusDTO.setType("1");
                statusDTO.setTitle("未发货");
            }
            else {
                statusDTO.setClassfy("state-nfh");
                statusDTO.setMsg("待核销,请到核销点进行核销");
                statusDTO.setType("1");
                statusDTO.setTitle("待核销");
            }
        }
        else if (OrderInfoEnum.STATUS_1.getValue().equals(order.getStatus())) {
            statusDTO.setClassfy("state-ysh");
            statusDTO.setMsg("服务商已发货");
            statusDTO.setType("2");
            statusDTO.setTitle("待收货");
        }
        else if (OrderInfoEnum.STATUS_2.getValue().equals(order.getStatus())) {
            statusDTO.setClassfy("state-ypj");
            statusDTO.setMsg("已收货,快去评价一下吧");
            statusDTO.setType("3");
            statusDTO.setTitle("待评价");
        }
        else if (OrderInfoEnum.STATUS_3.getValue().equals(order.getStatus())) {
            statusDTO.setClassfy("state-ytk");
            statusDTO.setMsg("交易完成,感谢您的支持");
            statusDTO.setType("4");
            statusDTO.setTitle("交易完成");
        }
        if (PayTypeEnum.WEIXIN.getValue().equals(order.getPayType())) {
            statusDTO.setPayType("微信支付");
        }
        else if (PayTypeEnum.YUE.getValue().equals(order.getPayType())) {
            statusDTO.setPayType("余额支付");
        }
        else {
            statusDTO.setPayType("积分支付");
        }
        order.setStatusDto(statusDTO);
        return order;
    }
    
    public void paySuccess(final String orderId, final String payType) {
        final StoreOrderQueryVo orderInfo = this.getOrderInfo(orderId, null);
        final LambdaQueryWrapper<StoreOrder> wrapper = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        wrapper.eq(StoreOrder::getOrderId, orderId);
        final StoreOrder storeOrder = new StoreOrder();
        storeOrder.setPaid(OrderInfoEnum.PAY_STATUS_1.getValue());
        storeOrder.setPayType(payType);
        storeOrder.setPayTime(new Date());
        this.yxStoreOrderMapper.update(storeOrder, (Wrapper)wrapper);
        this.userService.incPayCount(orderInfo.getUid());
        this.orderStatusService.create(orderInfo.getId(), OrderLogEnum.PAY_ORDER_SUCCESS.getValue(), OrderLogEnum.PAY_ORDER_SUCCESS.getDesc());
        if (orderInfo.getCombinationId() > 0L) {
            this.pinkService.createPink(orderInfo);
        }
        if (orderInfo.getBargainId() > 0L) {
            this.storeBargainUserService.setBargainUserStatus(orderInfo.getBargainId(), orderInfo.getUid());
        }
        final ShopUser userInfo = (ShopUser)this.userService.getById((Serializable)orderInfo.getUid());
        String payTypeMsg = PayTypeEnum.WEIXIN.getDesc();
        if (PayTypeEnum.YUE.getValue().equals(payType)) {
            payTypeMsg = PayTypeEnum.YUE.getDesc();
        }
        this.billService.expend(userInfo.getUid(), "购买商品", BillDetailEnum.CATEGORY_1.getValue(), BillDetailEnum.TYPE_3.getValue(), orderInfo.getPayPrice().doubleValue(), userInfo.getNowMoney().doubleValue(), payTypeMsg + orderInfo.getPayPrice() + "元购买商品");
        final TemplateBean templateBean = TemplateBean.builder().orderId(orderInfo.getOrderId()).price(orderInfo.getPayPrice().toString()).uid(orderInfo.getUid()).templateType(TemplateListenEnum.TYPE_1.getValue()).build();
        this.publisher.publishEvent((ApplicationEvent)new TemplateEvent(this, templateBean));
    }
    
    public String aliPay(final String orderId) throws Exception {
        final AlipayConfig alipay = this.alipayService.find();
        if (ObjectUtil.isNull(alipay)) {
            throw new EshopException("请先配置支付宝");
        }
        final StoreOrderQueryVo orderInfo = this.getOrderInfo(orderId, null);
        if (ObjectUtil.isNull(orderInfo)) {
            throw new EshopException("订单不存在");
        }
        if (OrderInfoEnum.PAY_STATUS_1.getValue().equals(orderInfo.getPaid())) {
            throw new EshopException("该订单已支付");
        }
        if (orderInfo.getPayPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new EshopException("该支付无需支付");
        }
        final TradeVo trade = new TradeVo();
        trade.setOutTradeNo(orderId);
        final String payUrl = this.alipayService.toPayAsWeb(alipay, trade);
        return payUrl;
    }
    
    public void yuePay(final String orderId, final Long uid) {
        final StoreOrderQueryVo orderInfo = this.getOrderInfo(orderId, uid);
        if (ObjectUtil.isNull(orderInfo)) {
            throw new EshopException("订单不存在");
        }
        if (OrderInfoEnum.PAY_STATUS_1.getValue().equals(orderInfo.getPaid())) {
            throw new EshopException("该订单已支付");
        }
        final UserQueryVo userInfo = this.userService.getYxUserById(uid);
        if (userInfo.getNowMoney().compareTo(orderInfo.getPayPrice()) < 0) {
            throw new EshopException("余额不足");
        }
        this.userService.decPrice(uid, orderInfo.getPayPrice());
        this.paySuccess(orderInfo.getOrderId(), PayTypeEnum.YUE.getValue());
    }

    //积分支付
    public void integralPay(final String orderId, final Long uid) {
        StoreOrderQueryVo orderInfo = this.getOrderInfo(orderId, uid);
        if (ObjectUtil.isNull(orderInfo)) {
            throw new EshopException("订单不存在");
        }
        if (OrderInfoEnum.PAY_STATUS_1.getValue().equals(orderInfo.getPaid())) {
            throw new EshopException("该订单已支付");
        }
        //处理订单
        orderInfo = this.handleOrder(orderInfo);
        //判断购物车中的每个商品是不是都是支持积分兑换的，有一个不支持都直接报错
        orderInfo.getCartInfo().forEach(cart -> {
            if (cart.getProductInfo().getIsIntegral() == 0) {
                throw new EshopException("该商品不为积分商品");
            }
            else {
                return;
            }
        });
        //查询该用户
        final ShopUser userInfo = (ShopUser)this.userService.getById((Serializable)uid);
        //判断积分是否足够
        if (userInfo.getIntegral().compareTo(orderInfo.getPayIntegral()) < 0) {
            throw new EshopException("积分不足");
        }
        //计算出使用积分后的剩余积分，并且重新赋值，
        final BigDecimal newIntegral = NumberUtil.sub((Number)userInfo.getIntegral(), (Number)orderInfo.getPayIntegral());
        userInfo.setIntegral(newIntegral);
        this.userService.updateById(userInfo);
        this.billService.expend(userInfo.getUid(), "兑换商品", BillDetailEnum.CATEGORY_2.getValue(), BillDetailEnum.TYPE_8.getValue(), orderInfo.getPayIntegral().doubleValue(), newIntegral.doubleValue(), "兑换商品扣除" + orderInfo.getPayIntegral().doubleValue() + "积分");
        this.paySuccess(orderInfo.getOrderId(), PayTypeEnum.INTEGRAL.getValue());
    }

    //unique就是key
    public StoreOrderQueryVo getOrderInfo(final String unique, final Long uid) {
        final LambdaQueryWrapper<StoreOrder> wrapper = (LambdaQueryWrapper<StoreOrder>)new LambdaQueryWrapper();
        final LambdaQueryWrapper lambdaQueryWrapper;
        //这里查询条件挺奇怪的，就是orderId以及unique与这里的unique就行比较
        wrapper.and(i -> ((((i.eq(StoreOrder::getOrderId, unique)).or()).eq(StoreOrder::getUnique, unique)).or()).eq(StoreOrder::getExtendOrderId, unique));
        if (uid != null) {
            wrapper.eq(StoreOrder::getUid, uid);
        }
        //查到值后用转换器转换成VO对象，然后返回
        return (StoreOrderQueryVo)this.generator.convert(this.yxStoreOrderMapper.selectOne((Wrapper)wrapper), (Class)StoreOrderQueryVo.class);
    }
    
    private void gainUserIntegral(final StoreOrderQueryVo order) {
        if (order.getGainIntegral().compareTo(BigDecimal.ZERO) > 0) {
            final ShopUser user = (ShopUser)this.userService.getById((Serializable)order.getUid());
            final BigDecimal newIntegral = NumberUtil.add((Number)user.getIntegral(), (Number)order.getGainIntegral());
            user.setIntegral(newIntegral);
            user.setUid(order.getUid());
            this.userService.updateById(user);
            this.billService.income(user.getUid(), "购买商品赠送积分", BillDetailEnum.CATEGORY_2.getValue(), BillDetailEnum.TYPE_9.getValue(), order.getGainIntegral().doubleValue(), newIntegral.doubleValue(), "购买商品赠送" + order.getGainIntegral() + "积分", order.getId().toString());
        }
    }
    
    public void deStockIncSale(final List<StoreCartQueryVo> cartInfo) {
        for (final StoreCartQueryVo storeCartVO : cartInfo) {
            final Long combinationId = storeCartVO.getCombinationId();
            final Long seckillId = storeCartVO.getSeckillId();
            final Long bargainId = storeCartVO.getBargainId();
            if (combinationId != null && combinationId > 0L) {
                this.productService.decProductStock(storeCartVO.getCartNum(), storeCartVO.getProductId(), storeCartVO.getProductAttrUnique(), combinationId, ProductTypeEnum.COMBINATION.getValue());
            }
            else if (seckillId != null && seckillId > 0L) {
                this.productService.decProductStock(storeCartVO.getCartNum(), storeCartVO.getProductId(), storeCartVO.getProductAttrUnique(), seckillId, ProductTypeEnum.SECKILL.getValue());
            }
            else if (bargainId != null && bargainId > 0L) {
                this.storeBargainService.decStockIncSales(storeCartVO.getCartNum(), bargainId);
            }
            else {
                this.productService.decProductStock(storeCartVO.getCartNum(), storeCartVO.getProductId(), storeCartVO.getProductAttrUnique(), 0L, "");
            }
        }
    }

    //用户积分减去使用的积分，并且更新对应数据到user_bill表中
    private void decIntegral(final ShopUser userInfo, final double usedIntegral, final double deductionPrice) {
        //让当前用户的积分总数减去使用的积分
        this.userService.decIntegral(userInfo.getUid(), usedIntegral);
        //bill表存入对应积分使用数据
        this.billService.expend(userInfo.getUid(), "积分抵扣", BillDetailEnum.CATEGORY_2.getValue(), BillDetailEnum.TYPE_8.getValue(), usedIntegral, userInfo.getIntegral().doubleValue(), "购买商品使用" + usedIntegral + "积分抵扣" + deductionPrice + "元");
    }
    
    private BigDecimal getGainIntegral(final List<StoreCartQueryVo> cartInfo) {
        BigDecimal gainIntegral = BigDecimal.ZERO;
        for (final StoreCartQueryVo cart : cartInfo) {
            if (cart.getCombinationId() <= 0L && cart.getSeckillId() <= 0L) {
                if (cart.getBargainId() > 0L) {
                    continue;
                }
                BigDecimal cartInfoGainIntegral = BigDecimal.ZERO;
                final Double gain = cart.getProductInfo().getGiveIntegral().doubleValue();
                if (gain > 0.0) {
                    cartInfoGainIntegral = NumberUtil.round(NumberUtil.mul((Number)cart.getCartNum(), (Number)gain), 2);
                }
                gainIntegral = NumberUtil.add((Number)gainIntegral, (Number)cartInfoGainIntegral);
            }
        }
        return gainIntegral;
    }
    
    private void regressionCoupon(final StoreOrderQueryVo order, final Integer type) {
        if (type == 0) {
            if (OrderInfoEnum.PAY_STATUS_1.getValue().equals(order.getPaid()) || OrderStatusEnum.STATUS_MINUS_2.getValue().equals(order.getStatus())) {
                return;
            }
        }
        else if (!OrderInfoEnum.PAY_STATUS_1.getValue().equals(order.getPaid()) || !OrderInfoEnum.REFUND_STATUS_2.getValue().equals(order.getRefundStatus())) {
            return;
        }
        if (order.getCouponId() != null && order.getCouponId() > 0) {
            final StoreCouponUser couponUser = (StoreCouponUser)this.couponUserService.getOne(((Wrappers.<StoreCouponUser>lambdaQuery().eq(StoreCouponUser::getId, order.getCouponId())).eq(StoreCouponUser::getStatus, CouponEnum.STATUS_1.getValue())).eq(StoreCouponUser::getUid, order.getUid()));
            if (ObjectUtil.isNotNull(couponUser)) {
                final StoreCouponUser storeCouponUser = new StoreCouponUser();
                storeCouponUser.setStatus(CouponEnum.STATUS_0.getValue());
                storeCouponUser.setUseTime(null);
                this.couponUserService.update(storeCouponUser, (Wrapper)(Wrappers.<StoreCouponUser>lambdaQuery().eq(StoreCouponUser::getId, order.getCouponId())).eq(StoreCouponUser::getUid, order.getUid()));
            }
        }
    }
    
    private void regressionStock(final StoreOrderQueryVo order, final Integer type) {
        if (type == 0) {
            if (OrderInfoEnum.PAY_STATUS_1.getValue().equals(order.getPaid()) || OrderStatusEnum.STATUS_MINUS_2.getValue().equals(order.getStatus())) {
                return;
            }
        }
        else if (!OrderInfoEnum.PAY_STATUS_1.getValue().equals(order.getPaid()) || !OrderInfoEnum.REFUND_STATUS_2.getValue().equals(order.getRefundStatus())) {
            return;
        }
        final LambdaQueryWrapper<StoreOrderCartInfo> wrapper = (LambdaQueryWrapper<StoreOrderCartInfo>)new LambdaQueryWrapper();
        wrapper.in(StoreOrderCartInfo::getCartId, (Collection)Arrays.asList(order.getCartId().split(",")));
        final List<StoreOrderCartInfo> cartInfoList = (List<StoreOrderCartInfo>)this.orderCartInfoService.list((Wrapper)wrapper);
        for (final StoreOrderCartInfo cartInfo : cartInfoList) {
            final StoreCartQueryVo cart = (StoreCartQueryVo)JSONObject.parseObject(cartInfo.getCartInfo(), (Class)StoreCartQueryVo.class);
            if (order.getCombinationId() != null && order.getCombinationId() > 0L) {
                this.productService.incProductStock(cart.getCartNum(), cart.getProductId(), cart.getProductAttrUnique(), order.getCombinationId(), ProductTypeEnum.COMBINATION.getValue());
            }
            else if (order.getSeckillId() != null && order.getSeckillId() > 0L) {
                this.productService.incProductStock(cart.getCartNum(), cart.getProductId(), cart.getProductAttrUnique(), order.getSeckillId(), ProductTypeEnum.SECKILL.getValue());
            }
            else if (order.getBargainId() != null && order.getBargainId() > 0L) {
                this.storeBargainService.incStockDecSales(cart.getCartNum(), order.getBargainId());
            }
            else {
                this.productService.incProductStock(cart.getCartNum(), cart.getProductId(), cart.getProductAttrUnique(), 0L, null);
            }
        }
    }
    
    private void regressionIntegral(final StoreOrderQueryVo order, final Integer type) {
        if (type == 0) {
            if (OrderInfoEnum.PAY_STATUS_1.getValue().equals(order.getPaid()) || OrderStatusEnum.STATUS_MINUS_2.getValue().equals(order.getStatus())) {
                return;
            }
        }
        else if (!OrderInfoEnum.PAY_STATUS_1.getValue().equals(order.getPaid()) || !OrderInfoEnum.REFUND_STATUS_2.getValue().equals(order.getRefundStatus())) {
            return;
        }
        if (order.getPayIntegral().compareTo(BigDecimal.ZERO) > 0) {
            order.setUseIntegral(order.getPayIntegral());
        }
        if (order.getUseIntegral().compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }
        if (!OrderStatusEnum.STATUS_MINUS_2.getValue().equals(order.getStatus()) && !OrderInfoEnum.REFUND_STATUS_2.getValue().equals(order.getRefundStatus()) && order.getBackIntegral().compareTo(BigDecimal.ZERO) > 0) {
            return;
        }
        final ShopUser shopUser = (ShopUser)this.userService.getById((Serializable)order.getUid());
        final BigDecimal newIntegral = NumberUtil.add((Number)order.getUseIntegral(), (Number)shopUser.getIntegral());
        shopUser.setIntegral(newIntegral);
        this.userService.updateById(shopUser);
        this.billService.income(shopUser.getUid(), "积分回退", BillDetailEnum.CATEGORY_2.getValue(), BillDetailEnum.TYPE_8.getValue(), order.getUseIntegral().doubleValue(), newIntegral.doubleValue(), "购买商品失败,回退积分" + order.getUseIntegral(), order.getId().toString());
        final StoreOrder storeOrder = new StoreOrder();
        storeOrder.setBackIntegral(order.getUseIntegral());
        storeOrder.setId(order.getId());
        this.yxStoreOrderMapper.updateById(storeOrder);
    }
    
    private CacheDto getCacheOrderInfo(final Long uid, final String key) {
        final Object obj = this.redisUtils.get("yshop:order" + uid + key);
        if (obj == null) {
            return null;
        }
        return (CacheDto)JSON.parseObject(obj.toString(), (Class)CacheDto.class);
    }
    
    private void delCacheOrderInfo(final Long uid, final String key) {
        this.redisUtils.del(new String[] { "yshop:order" + uid + key });
    }
    
    private String cacheOrderInfo(final Long uid, final List<StoreCartQueryVo> cartInfo, final PriceGroupDto priceGroup, final OtherDto other) {
        //随机生成一个简单的UUID作为key
        final String key = IdUtil.simpleUUID();
        final CacheDto cacheDTO = new CacheDto();
        cacheDTO.setCartInfo(cartInfo);
        cacheDTO.setPriceGroup(priceGroup);
        cacheDTO.setOther(other);
        this.redisUtils.set("yshop:order" + uid + key, JSON.toJSONString(cacheDTO), 600L);
        return key;
    }
    
    private PriceGroupDto getOrderPriceGroup(final List<StoreCartQueryVo> cartInfo, final UserAddress userAddress) {
        BigDecimal storePostage = BigDecimal.ZERO;
        //获取出店铺包多少邮费
        final String storeFreePostageStr = this.systemConfigService.getData("store_free_postage");
        BigDecimal storeFreePostage = BigDecimal.ZERO;
        //判断获取出来的店铺包多少邮费是否参数正餐
        if (NumberUtil.isNumber((CharSequence)storeFreePostageStr) && StrUtil.isNotBlank((CharSequence)storeFreePostageStr)) {
            storeFreePostage = new BigDecimal(storeFreePostageStr);
        }
        //获取出该购物车总价格
        BigDecimal totalPrice = this.getOrderSumPrice(cartInfo, "truePrice");
        //计算出总的成本价
        final BigDecimal costPrice = this.getOrderSumPrice(cartInfo, "costPrice");
        //计算出总的VIP价格
        final BigDecimal vipPrice = this.getOrderSumPrice(cartInfo, "vipTruePrice");
        //计算出需要支付的总的积分
        final BigDecimal payIntegral = this.getOrderSumPrice(cartInfo, "payIntegral");
        //判断店家包的邮费是否大于0 同时 购物车总价格<=邮费
        if (storeFreePostage.compareTo(BigDecimal.ZERO) != 0 && totalPrice.compareTo(storeFreePostage) <= 0) {
            //那么还是计算邮费
            storePostage = this.handlePostage(cartInfo, userAddress);
        }
        //如果购物车列表只有一个，而且该购物车商品开启积分兑换
        if (cartInfo.size() == 1 && cartInfo.get(0).getProductInfo().getIsIntegral() != null && cartInfo.get(0).getProductInfo().getIsIntegral() == 1) {
            //那么totalPrice购物车总价格设置为0
            totalPrice = BigDecimal.ZERO;
        }
        final PriceGroupDto priceGroupDTO = new PriceGroupDto();
        priceGroupDTO.setStorePostage(storePostage);
        priceGroupDTO.setStoreFreePostage(storeFreePostage);
        priceGroupDTO.setTotalPrice(totalPrice);
        priceGroupDTO.setCostPrice(costPrice);
        priceGroupDTO.setVipPrice(vipPrice);
        priceGroupDTO.setPayIntegral(payIntegral);
        return priceGroupDTO;
    }

    //根据地址计算邮费
    private BigDecimal handlePostage(final List<StoreCartQueryVo> cartInfo, final UserAddress userAddress) {
        BigDecimal storePostage = BigDecimal.ZERO;
        if (userAddress != null) {
            //如果用户地址都没有城市ID，就直接返回0邮费
            if (userAddress.getCityId() == null) {
                return storePostage;
            }
            //获取城市ID
            final int cityId = userAddress.getCityId();
            final List<Integer> citys = new ArrayList<Integer>();
            citys.add(cityId);
            citys.add(0);
            final List<StoreProductQueryVo> storeProductVOList = cartInfo.stream().map(StoreCartQueryVo::getProductInfo).collect(Collectors.toList());
            final List<Integer> tempIdS = storeProductVOList.stream().map(StoreProductQueryVo::getTempId).collect(Collectors.toList());
            final List<ShippingTemplates> shippingTemplatesList = (List<ShippingTemplates>)this.shippingTemplatesService.list(Wrappers.<ShippingTemplates>lambdaQuery().in(ShippingTemplates::getId, (Collection)tempIdS));
            final List<ShippingTemplatesRegion> shippingTemplatesRegionList = (List<ShippingTemplatesRegion>)this.shippingTemplatesRegionService.list(((Wrappers.<ShippingTemplatesRegion>lambdaQuery().in(ShippingTemplatesRegion::getTempId, (Collection)tempIdS)).in(ShippingTemplatesRegion::getCityId, (Collection)citys)).orderByAsc(ShippingTemplatesRegion::getCityId));
            final Map<Integer, Integer> shippingTemplatesMap = shippingTemplatesList.stream().collect(Collectors.toMap(ShippingTemplates::getId, ShippingTemplates::getType));
            final Map<Integer, ShippingTemplatesRegion> shippingTemplatesRegionMap = shippingTemplatesRegionList.stream().collect(Collectors.toMap(ShippingTemplatesRegion::getTempId, YxShippingTemplatesRegion -> YxShippingTemplatesRegion, (key1, key2) -> key2));
            final Map<Integer, TemplateDto> templateDTOMap = new HashMap<Integer, TemplateDto>();
            for (final StoreCartQueryVo storeCartVO : cartInfo) {
                final Integer tempId = storeCartVO.getProductInfo().getTempId();
                if (tempId == null) {
                    return storePostage;
                }
                double num = 0.0;
                if (ShippingTempEnum.TYPE_1.getValue().equals(shippingTemplatesMap.get(tempId))) {
                    num = storeCartVO.getCartNum();
                }
                else if (ShippingTempEnum.TYPE_2.getValue().equals(shippingTemplatesMap.get(tempId))) {
                    num = NumberUtil.mul((Number)storeCartVO.getCartNum(), (Number)storeCartVO.getProductInfo().getAttrInfo().getWeight()).doubleValue();
                }
                else if (ShippingTempEnum.TYPE_3.getValue().equals(shippingTemplatesMap.get(tempId))) {
                    num = NumberUtil.mul((Number)storeCartVO.getCartNum(), (Number)storeCartVO.getProductInfo().getAttrInfo().getVolume()).doubleValue();
                }
                final ShippingTemplatesRegion shippingTemplatesRegion = shippingTemplatesRegionMap.get(tempId);
                final BigDecimal price = NumberUtil.round(NumberUtil.mul((Number)storeCartVO.getCartNum(), (Number)storeCartVO.getTruePrice()), 2);
                if (!templateDTOMap.containsKey(tempId)) {
                    final TemplateDto templateDTO = TemplateDto.builder().number(num).price(price).first(shippingTemplatesRegion.getFirst().doubleValue()).firstPrice(shippingTemplatesRegion.getFirstPrice())._continue(shippingTemplatesRegion.getContinues().doubleValue()).continuePrice(shippingTemplatesRegion.getContinuePrice()).tempId(tempId).cityId(cityId).build();
                    templateDTOMap.put(tempId, templateDTO);
                }
                else {
                    final TemplateDto templateDTO = templateDTOMap.get(tempId);
                    templateDTO.setNumber(templateDTO.getNumber() + num);
                    templateDTO.setPrice(NumberUtil.add((Number)templateDTO.getPrice().doubleValue(), (Number)price));
                }
            }
            for (final Map.Entry<Integer, TemplateDto> entry : templateDTOMap.entrySet()) {
                final Integer mapKey = entry.getKey();
                final TemplateDto mapValue = entry.getValue();
                final int count = this.shippingTemplatesFreeService.count((Wrapper)(((Wrappers.<ShippingTemplatesFree>lambdaQuery().eq(ShippingTemplatesFree::getTempId, mapValue.getTempId())).eq(ShippingTemplatesFree::getCityId, mapValue.getCityId())).le(ShippingTemplatesFree::getNumber, mapValue.getNumber())).le(ShippingTemplatesFree::getPrice, mapValue.getPrice()));
                if (count > 0) {
                    templateDTOMap.remove(mapKey);
                }
            }
            boolean isFirst = true;
            for (final TemplateDto templateDTO2 : templateDTOMap.values()) {
                if (isFirst) {
                    if (Double.compare(templateDTO2.getNumber(), templateDTO2.getFirst()) <= 0) {
                        storePostage = NumberUtil.round(NumberUtil.add((Number)storePostage, (Number)templateDTO2.getFirstPrice()), 2);
                    }
                    else {
                        final BigDecimal fristPrice = NumberUtil.add((Number)storePostage, (Number)templateDTO2.getFirstPrice());
                        if (templateDTO2.get_continue() <= 0.0) {
                            storePostage = fristPrice;
                        }
                        else {
                            final double average = Math.ceil(NumberUtil.div(NumberUtil.sub(templateDTO2.getNumber(), templateDTO2.getFirst()), (double)templateDTO2.get_continue()));
                            storePostage = NumberUtil.add((Number)fristPrice, (Number)NumberUtil.mul((Number)average, (Number)templateDTO2.getContinuePrice()));
                        }
                    }
                    isFirst = false;
                }
                else {
                    if (templateDTO2.get_continue() <= 0.0) {
                        continue;
                    }
                    final double average2 = Math.ceil(NumberUtil.div(templateDTO2.getNumber(), templateDTO2.get_continue()));
                    storePostage = NumberUtil.add((Number)storePostage.doubleValue(), (Number)NumberUtil.mul((Number)average2, (Number)templateDTO2.getContinuePrice()));
                }
            }
        }
        return storePostage;
    }

    //这个方法就是复用去计算一些价格的，计算一个购物车列表里面的总合价格
    private BigDecimal getOrderSumPrice(final List<StoreCartQueryVo> cartInfo, final String key) {
        BigDecimal sumPrice = BigDecimal.ZERO;
        //计算总的真实价
        if ("truePrice".equals(key)) {
            for (final StoreCartQueryVo storeCart : cartInfo) {
                sumPrice = NumberUtil.add((Number)sumPrice, (Number)NumberUtil.mul((Number)storeCart.getCartNum(), (Number)storeCart.getTruePrice()));
            }
        }
        //计算总的成本价
        else if ("costPrice".equals(key)) {
            for (final StoreCartQueryVo storeCart : cartInfo) {
                sumPrice = NumberUtil.add((Number)sumPrice, (Number)NumberUtil.mul((Number)storeCart.getCartNum(), (Number)storeCart.getCostPrice()));
            }
        }
        //计算总的vip价格
        else if ("vipTruePrice".equals(key)) {
            for (final StoreCartQueryVo storeCart : cartInfo) {
                sumPrice = NumberUtil.add((Number)sumPrice, (Number)NumberUtil.mul((Number)storeCart.getCartNum(), (Number)storeCart.getVipTruePrice()));
            }
        }
        //计算总的积分
        else if ("payIntegral".equals(key)) {
            for (final StoreCartQueryVo storeCart : cartInfo) {
                sumPrice = NumberUtil.add((Number)sumPrice, (Number)NumberUtil.mul((Number)storeCart.getCartNum(), (Number)storeCart.getProductInfo().getAttrInfo().getIntegral()));
            }
        }
        return sumPrice;
    }

    public OrderCountDto getOrderCount() {
        List<CountDto> nameList = this.storeCartService.findCateName();
        Map<String, Integer> childrenMap = new HashMap();
        nameList.forEach((i) -> {
            if (i != null) {
                if (childrenMap.containsKey(i.getCatename())) {
                    childrenMap.put(i.getCatename(), (Integer)childrenMap.get(i.getCatename()) + 1);
                } else {
                    childrenMap.put(i.getCatename(), 1);
                }
            }

        });
        List<OrderCountDto.OrderCountData> list = new ArrayList();
        List<String> columns = new ArrayList();
        childrenMap.forEach((k, v) -> {
            OrderCountDto.OrderCountData orderCountData = new OrderCountDto.OrderCountData();
            orderCountData.setName(k);
            orderCountData.setValue(v);
            columns.add(k);
            list.add(orderCountData);
        });
        OrderCountDto orderCountDto = new OrderCountDto();
        orderCountDto.setColumn(columns);
        orderCountDto.setOrderCountDatas(list);
        return orderCountDto;
    }
    
    public OrderTimeDataDto getOrderTimeData() {
        final OrderTimeDataDto orderTimeDataDto = new OrderTimeDataDto();
        final ShoperOrderTimeDataVo shoperOrderTimeData = this.getShoperOrderTimeData();
        BeanUtil.copyProperties(shoperOrderTimeData, orderTimeDataDto, new String[0]);
        orderTimeDataDto.setUserCount(this.userService.count());
        orderTimeDataDto.setOrderCount(this.count());
        orderTimeDataDto.setPriceCount(this.yxStoreOrderMapper.sumTotalPrice());
        orderTimeDataDto.setGoodsCount(this.productService.count());
        return orderTimeDataDto;
    }
    
    public Map<String, Object> chartCount() {
        final Map<String, Object> map = new LinkedHashMap<String, Object>();
        final Date nowMonth = (Date)DateUtil.beginOfMonth(new Date());
        map.put("chart", this.yxStoreOrderMapper.chartList(nowMonth));
        map.put("chartT", this.yxStoreOrderMapper.chartListT(nowMonth));
        return map;
    }
    
    public void retrunStock(final String orderId) {
        final StoreOrderQueryVo order = this.getOrderInfo(orderId, null);
        this.regressionIntegral(order, 1);
        this.regressionStock(order, 1);
        this.regressionCoupon(order, 1);
    }
    
    public Map<String, Object> queryAll(final StoreOrderQueryCriteria criteria, final Pageable pageable) {
        this.getPage(pageable);
        final PageInfo<StoreOrder> page = (PageInfo<StoreOrder>)new PageInfo((List)this.queryAll(criteria));
        final List<StoreOrderDto> storeOrderDTOS = new ArrayList<StoreOrderDto>();
        for (final StoreOrder storeOrder : page.getList()) {
            this.orderList(storeOrderDTOS, storeOrder);
        }
        final Map<String, Object> map = new LinkedHashMap<String, Object>(2);
        map.put("content", storeOrderDTOS);
        map.put("totalElements", page.getTotal());
        return map;
    }
    
    public List<StoreOrder> queryAll(final StoreOrderQueryCriteria criteria) {
        return (List<StoreOrder>)((StoreOrderMapper)this.baseMapper).selectList((Wrapper)QueryHelpPlus.getPredicate(StoreOrder.class, criteria));
    }
    
    @Transactional(rollbackFor = { Exception.class })
    public void update(final StoreOrder resources) {
        final StoreOrder storeOrder = (StoreOrder)this.getById((Serializable)resources.getId());
        final StoreOrder storeOrder2 = (StoreOrder)this.getOne(Wrappers.<StoreOrder>lambdaQuery().eq(StoreOrder::getUnique, resources.getUnique()));
        if (storeOrder2 != null && !storeOrder2.getId().equals(storeOrder.getId())) {
            throw new EntityExistException((Class)StoreOrder.class, "unique", resources.getUnique());
        }
        storeOrder.copy(resources);
        this.saveOrUpdate(storeOrder);
    }
    
    public void download(final List<StoreOrderDto> all, final HttpServletResponse response) throws IOException {
        final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (final StoreOrderDto yxStoreOrder : all) {
            final Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("订单号", yxStoreOrder.getOrderId());
            map.put("用户id", yxStoreOrder.getUid());
            map.put("用户姓名", yxStoreOrder.getRealName());
            map.put("用户电话", yxStoreOrder.getUserPhone());
            map.put("详细地址", yxStoreOrder.getUserAddress());
            map.put("购物车id", yxStoreOrder.getCartId());
            map.put("运费金额", yxStoreOrder.getFreightPrice());
            map.put("订单商品总数", yxStoreOrder.getTotalNum());
            map.put("订单总价", yxStoreOrder.getTotalPrice());
            map.put("邮费", yxStoreOrder.getTotalPostage());
            map.put("实际支付金额", yxStoreOrder.getPayPrice());
            map.put("支付邮费", yxStoreOrder.getPayPostage());
            map.put("抵扣金额", yxStoreOrder.getDeductionPrice());
            map.put("优惠券id", yxStoreOrder.getCouponId());
            map.put("优惠券金额", yxStoreOrder.getCouponPrice());
            map.put("支付状态", yxStoreOrder.getPaid());
            map.put("支付时间", yxStoreOrder.getPayTime());
            map.put("支付方式", yxStoreOrder.getPayType());
            map.put("订单状态（-1 : 申请退款 -2 : 退货成功 0：待发货；1：待收货；2：已收货；3：待评价；-1：已退款）", yxStoreOrder.getStatus());
            map.put("0 未退款 1 申请中 2 已退款", yxStoreOrder.getRefundStatus());
            map.put("退款图片", yxStoreOrder.getRefundReasonWapImg());
            map.put("退款用户说明", yxStoreOrder.getRefundReasonWapExplain());
            map.put("退款时间", yxStoreOrder.getRefundReasonTime());
            map.put("前台退款原因", yxStoreOrder.getRefundReasonWap());
            map.put("不退款的理由", yxStoreOrder.getRefundReason());
            map.put("退款金额", yxStoreOrder.getRefundPrice());
            map.put("快递公司编号", yxStoreOrder.getDeliverySn());
            map.put("快递名称/送货人姓名", yxStoreOrder.getDeliveryName());
            map.put("发货类型", yxStoreOrder.getDeliveryType());
            map.put("快递单号/手机号", yxStoreOrder.getDeliveryId());
            map.put("消费赚取积分", yxStoreOrder.getGainIntegral());
            map.put("使用积分", yxStoreOrder.getUseIntegral());
            map.put("给用户退了多少积分", yxStoreOrder.getBackIntegral());
            map.put("备注", yxStoreOrder.getMark());
            map.put("唯一id(md5加密)类似id", yxStoreOrder.getUnique());
            map.put("管理员备注", yxStoreOrder.getRemark());
            map.put("商户ID", yxStoreOrder.getMerId());
            map.put(" isMerCheck", yxStoreOrder.getIsMerCheck());
            map.put("拼团产品id0一般产品", yxStoreOrder.getCombinationId());
            map.put("拼团id 0没有拼团", yxStoreOrder.getPinkId());
            map.put("成本价", yxStoreOrder.getCost());
            map.put("秒杀产品ID", yxStoreOrder.getSeckillId());
            map.put("砍价id", yxStoreOrder.getBargainId());
            map.put("核销码", yxStoreOrder.getVerifyCode());
            map.put("门店id", yxStoreOrder.getStoreId());
            map.put("配送方式 1=快递 ，2=门店自提", yxStoreOrder.getShippingType());
            map.put("支付渠道(0微信公众号1微信小程序)", yxStoreOrder.getIsChannel());
            map.put(" isRemind", yxStoreOrder.getIsRemind());
            list.add(map);
        }
        FileUtil.downloadExcel((List)list, response);
    }
    
    public StoreOrderDto getOrderDetail(final Long orderId) {
        final StoreOrder storeOrder = (StoreOrder)this.getById((Serializable)orderId);
        if (ObjectUtil.isEmpty(storeOrder)) {
            throw new BadRequestException("订单详情不存在");
        }
        final StoreOrderDto storeOrderDto = (StoreOrderDto)this.generator.convert(storeOrder, (Class)StoreOrderDto.class);
        final Integer _status = OrderUtil.orderStatus((int)storeOrder.getPaid(), (int)storeOrder.getStatus(), (int)storeOrder.getRefundStatus());
        if (storeOrder.getStoreId() > 0) {
            final String storeName = ((SystemStore)this.systemStoreService.getById((Serializable)storeOrder.getStoreId())).getName();
            storeOrderDto.setStoreName(storeName);
        }
        String orderStatusStr = OrderUtil.orderStatusStr((int)storeOrder.getPaid(), (int)storeOrder.getStatus(), (int)storeOrder.getShippingType(), (int)storeOrder.getRefundStatus());
        if (_status == 3) {
            final String refundTime = DateUtil.formatDateTime(storeOrder.getRefundReasonTime());
            final String str = orderStatusStr = "<b style='color:#f124c7'>申请退款</b><span>退款原因：" + storeOrder.getRefundReasonWap() + "</span><span>备注说明：" + storeOrder.getRefundReasonWapExplain() + "</span><span>退款时间：" + refundTime + "</span>";
        }
        storeOrderDto.setStatusName(orderStatusStr);
        storeOrderDto.set_status(_status);
        final String payTypeName = OrderUtil.payTypeName(storeOrder.getPayType(), (int)storeOrder.getPaid());
        storeOrderDto.setPayTypeName(payTypeName);
        storeOrderDto.setPinkName(this.orderType(storeOrder.getId(), storeOrder.getPinkId(), storeOrder.getCombinationId(), storeOrder.getSeckillId(), storeOrder.getBargainId(), storeOrder.getShippingType(), storeOrder.getPayIntegral()));
        final List<StoreOrderStatus> storeOrderStatuses = (List<StoreOrderStatus>)this.orderStatusService.list(Wrappers.<StoreOrderStatus>lambdaQuery().eq(StoreOrderStatus::getOid, storeOrder.getId()));
        final List<StoreOrderStatusDto> orderStatusDtos = (List<StoreOrderStatusDto>)this.generator.convert((List)storeOrderStatuses, (Class)StoreOrderStatusDto.class);
        storeOrderDto.setStoreOrderStatusList(orderStatusDtos);
        final List<StoreOrderCartInfo> cartInfos = (List<StoreOrderCartInfo>)this.storeOrderCartInfoService.list(Wrappers.<StoreOrderCartInfo>lambdaQuery().eq(StoreOrderCartInfo::getOid, storeOrder.getId()));
        final List<StoreOrderCartInfoDto> cartInfoDTOS = new ArrayList<StoreOrderCartInfoDto>();
        for (final StoreOrderCartInfo cartInfo : cartInfos) {
            final StoreOrderCartInfoDto cartInfoDTO = new StoreOrderCartInfoDto();
            cartInfoDTO.setCartInfoMap((Map<String, Object>)JSON.parseObject(cartInfo.getCartInfo()));
            cartInfoDTOS.add(cartInfoDTO);
        }
        storeOrderDto.setCartInfoList(cartInfoDTOS);
        storeOrderDto.setUserDTO((UserDto)this.generator.convert(this.userService.getById((Serializable)storeOrder.getUid()), (Class)UserDto.class));
        if (storeOrderDto.getUserDTO() == null) {
            storeOrderDto.setUserDTO(new UserDto());
        }
        return storeOrderDto;
    }
    
    public Map<String, Object> queryAll(final List<String> ids) {
        final List<StoreOrder> storeOrders = (List<StoreOrder>)this.list(Wrappers.<StoreOrder>lambdaQuery().in(StoreOrder::getOrderId, (Collection)ids));
        final List<StoreOrderDto> storeOrderDTOS = new ArrayList<StoreOrderDto>();
        for (final StoreOrder storeOrder : storeOrders) {
            this.orderList(storeOrderDTOS, storeOrder);
        }
        final Map<String, Object> map = new LinkedHashMap<String, Object>(2);
        map.put("content", storeOrderDTOS);
        return map;
    }
    
    private void orderList(final List<StoreOrderDto> storeOrderDTOS, final StoreOrder storeOrder) {
        final StoreOrderDto storeOrderDto = (StoreOrderDto)this.generator.convert(storeOrder, (Class)StoreOrderDto.class);
        final Integer _status = OrderUtil.orderStatus((int)storeOrder.getPaid(), (int)storeOrder.getStatus(), (int)storeOrder.getRefundStatus());
        if (storeOrder.getStoreId() > 0) {
            final String storeName = ((SystemStore)this.systemStoreService.getById((Serializable)storeOrder.getStoreId())).getName();
            storeOrderDto.setStoreName(storeName);
        }
        String orderStatusStr = OrderUtil.orderStatusStr((int)storeOrder.getPaid(), (int)storeOrder.getStatus(), (int)storeOrder.getShippingType(), (int)storeOrder.getRefundStatus());
        if (_status == 3) {
            final String refundTime = DateUtil.formatDateTime(storeOrder.getRefundReasonTime());
            final String str = orderStatusStr = "<b style='color:#f124c7'>申请退款</b><br/><span>退款原因：" + storeOrder.getRefundReasonWap() + "</span><br/><span>备注说明：" + storeOrder.getRefundReasonWapExplain() + "</span><br/><span>退款时间：" + refundTime + "</span><br/>";
        }
        storeOrderDto.setStatusName(orderStatusStr);
        storeOrderDto.set_status(_status);
        final String payTypeName = OrderUtil.payTypeName(storeOrder.getPayType(), (int)storeOrder.getPaid());
        storeOrderDto.setPayTypeName(payTypeName);
        storeOrderDto.setPinkName(this.orderType(storeOrder.getId(), storeOrder.getPinkId(), storeOrder.getCombinationId(), storeOrder.getSeckillId(), storeOrder.getBargainId(), storeOrder.getShippingType(), storeOrder.getPayIntegral()));
        final List<StoreOrderCartInfo> cartInfos = (List<StoreOrderCartInfo>)this.storeOrderCartInfoService.list(Wrappers.<StoreOrderCartInfo>lambdaQuery().eq(StoreOrderCartInfo::getOid, storeOrder.getId()));
        final List<StoreOrderCartInfoDto> cartInfoDTOS = new ArrayList<StoreOrderCartInfoDto>();
        for (final StoreOrderCartInfo cartInfo : cartInfos) {
            final StoreOrderCartInfoDto cartInfoDTO = new StoreOrderCartInfoDto();
            cartInfoDTO.setCartInfoMap((Map<String, Object>)JSON.parseObject(cartInfo.getCartInfo()));
            cartInfoDTOS.add(cartInfoDTO);
        }
        storeOrderDto.setCartInfoList(cartInfoDTOS);
        storeOrderDto.setUserDTO((UserDto)this.generator.convert(this.userService.getById((Serializable)storeOrder.getUid()), (Class)UserDto.class));
        if (storeOrderDto.getUserDTO() == null) {
            storeOrderDto.setUserDTO(new UserDto());
        }
        storeOrderDTOS.add(storeOrderDto);
    }
    
    private String orderType(final Long id, final Long pinkId, final Long combinationId, final Long seckillId, final Long bargainId, final Integer shippingType, final BigDecimal payIntegral) {
        String str = "[普通订单]";
        if (pinkId > 0L || combinationId > 0L) {
            final StorePink storePink = (StorePink)this.storePinkService.getOne(Wrappers.<StorePink>lambdaQuery().eq(StorePink::getOrderIdKey, id));
            if (ObjectUtil.isNull(storePink)) {
                str = "[拼团订单]";
            }
            else if (OrderInfoEnum.PINK_STATUS_1.getValue().equals(storePink.getStatus())) {
                str = "[拼团订单]正在进行中";
            }
            else if (OrderInfoEnum.PINK_STATUS_2.getValue().equals(storePink.getStatus())) {
                str = "[拼团订单]已完成";
            }
            else if (OrderInfoEnum.PINK_STATUS_3.getValue().equals(storePink.getStatus())) {
                str = "[拼团订单]未完成";
            }
            else {
                str = "[拼团订单]历史订单";
            }
        }
        else if (seckillId > 0L) {
            str = "[秒杀订单]";
        }
        else if (bargainId > 0L) {
            str = "[砍价订单]";
        }
        if (OrderInfoEnum.SHIPPIING_TYPE_2.getValue().equals(shippingType)) {
            str = "[核销订单]";
        }
        if (payIntegral.compareTo(new BigDecimal("0.00")) == 1) {
            str = "[积分兑换]";
        }
        return str;
    }
    
    static {
        log = LoggerFactory.getLogger((Class)StoreOrderServiceImpl.class);
    }
}
